【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()
相关推荐
江烽渔火8 分钟前
C++ 多态
开发语言·c++
m0_4902406724 分钟前
软件自动化测试(1):python+selenium自动化测试环境搭建
开发语言·python·selenium
2401_8582861137 分钟前
CD21.【C++ Dev】类和对象(12) 流插入运算符的重载
开发语言·c++·算法·类和对象·运算符重载
橘猫云计算机设计37 分钟前
基于ssm的食物营养成分数据分析平台设计与实现(源码+lw+部署文档+讲解),源码可白嫖!
后端·python·信息可视化·数据挖掘·数据分析·django·毕业设计
上理考研周导师1 小时前
【虚拟仪器技术】Labview虚拟仪器技术应用教程习题参考答案[13页]
服务器·开发语言
郭涤生1 小时前
Chapter 5: The Standard Library (C++20)_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
叶孤程1 小时前
Qt图形化界面为何总被“冷落“?
开发语言·c++·qt
葵野寺1 小时前
【多线程】线程池
java·开发语言·java-ee·web app
高林雨露2 小时前
Java 与 Kotlin 对比学习指南(二)
java·开发语言·kotlin
笑口常开xpr2 小时前
C 语 言 --- 整 形 提 升
c语言·开发语言