300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 【Python COM】Word 自动纵向合并相同内容单元格

【Python COM】Word 自动纵向合并相同内容单元格

时间:2018-12-27 10:56:04

相关推荐

【Python COM】Word 自动纵向合并相同内容单元格

背景

docxtempl库不支持动态纵向合并单元格,所以写了这段代码用来曲线救国。

使用方法

需要纵向合并的单元格加上在文本末尾加上“【纵向合并】”,然后调用此函数,就会自动纵向合并相同内容的单元格。

代码

需要安装pywin32库。

有一定概率会出现各种_err,一般再多试几次就能解决,原因不太清楚。

比较坑的一点是,如果表格里有合并的单元格,那么直接按行/列遍历会出错,因为被合并的单元格里除了第一个单元格之外,其他的单元格都被删掉了。微软也没给出什么 API 能判断单元格是否存在,只能用 try-catch 了。

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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。