【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()
相关推荐
fouryears_234171 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~1 小时前
C#---StopWatch类
开发语言·c#
lifallen3 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研3 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi3 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8243 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员3 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋4 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO4 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
鱼鱼说测试5 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php