使用場景
docxtempl
庫不支持動態縱向合并單元格,所以寫了這段代碼用來曲線救國。
使用方法
需要縱向合并的單元格加上在文本末尾加上“【縱向合并】”,然后調用此函數,就會自動縱向合并相同內容的單元格。
代碼
需要安裝 pywin32
庫。
有一定概率會出現各種 pywintypes.com_err
,一般再多試幾次就能解決,原因不太清楚。
def post_render(doc_path):def merge(cells: list):merge_cells.reverse()cell = merge_cells.pop()while merge_cells:cell.Merge(merge_cells.pop())word_app = win32com.client.Dispatch("Word.Application")word_app.Visible = Truedoc = word_app.Documents.Open(doc_path)tables = doc.Tablesfor table in tables:sleep(0.1)row_count = table.Rows.Countsleep(0.1)column_count = table.Columns.Count# 遍歷每一列for column_index in range(1, column_count+1):merge_cells = []merge_content = ''for row_index in range(1, row_count+1):# 由于這一行可能由于合并單元格而不存在,所以需要加 try-catch 測試try:cell = table.Cell(row_index, column_index)text: str = cell.Range.Textexcept:continueif '【縱向合并】' in text:text = text.replace('【縱向合并】', '').strip()text = text.replace('\r\x07', '') # 移除換行符,避免出現多余的空行cell.Range.Text = textif merge_content == text:table.Cell(row_index, column_index).Range.Text = ''merge_cells.append(cell)else:if len(merge_cells) > 1:merge(merge_cells)cell = table.Cell(row_index, column_index) # 合并單元格后原來的 Cell 會被刪除,需要重新取merge_content = textmerge_cells.clear()merge_cells.append(cell)if len(merge_cells) > 1:merge(merge_cells)doc.Save()doc.Close()# 按需調用 word_app.Quit()