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

使用场景

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

使用方法

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

代码

需要安装 pywin32 库。

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

python 复制代码
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 = True

    doc = word_app.Documents.Open(doc_path)
    tables = doc.Tables
    for table in tables:
        sleep(0.1)
        row_count = table.Rows.Count
        sleep(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.Text
                except:
                    continue
                if '【纵向合并】' in text:
                    text = text.replace('【纵向合并】', '').strip()
                    text = text.replace('\r\x07', '') # 移除换行符,避免出现多余的空行
                    cell.Range.Text = text
                    if 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 = text
                        merge_cells.clear()
                        merge_cells.append(cell)
            if len(merge_cells) > 1:
                merge(merge_cells)
    doc.Save()
    doc.Close()
    # 按需调用 word_app.Quit()
相关推荐
天佑木枫3 分钟前
15天Python入门系列 · 序
开发语言·python
happylifetree3 分钟前
Python017-第二章15.数据容器-dict常用操作
python
装不满的克莱因瓶18 分钟前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
宋拾壹1 小时前
同时添加多个类目
android·开发语言·javascript
IT知识分享1 小时前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python
lunzi_08261 小时前
【学习笔记】《Python编程 从入门到实践》第8章:函数定义、参数传递与模块导入
笔记·python·学习
凡人叶枫1 小时前
Effective C++ 条款04:确定对象被使用前已先被初始化
java·linux·开发语言·c++·嵌入式开发
杨运交1 小时前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证2 小时前
2026财务岗位如何快速提升自身能力
python
小小龙学IT2 小时前
Go 语言后端开发:从并发模型到生产落地的工程实践
开发语言·后端·golang