【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()
相关推荐
RaidenQ6 分钟前
2024.9.20 Python模式识别新国大EE5907,PCA主成分分析,LDA线性判别分析,GMM聚类分类,SVM支持向量机
python·算法·机器学习·支持向量机·分类·聚类
_平凡之路_13 分钟前
解决ubuntu22.04 gnome-terminal 无法启动的问题
linux·运维·python
豆本-豆豆奶15 分钟前
23个Python在自然语言处理中的应用实例
开发语言·python·自然语言处理·编程语音
NiNg_1_23419 分钟前
机器学习之Python中Scikit-Learn(sklearn)入门
python·机器学习·scikit-learn
曳渔21 分钟前
Java-数据结构-二叉树-习题(三)  ̄へ ̄
java·开发语言·数据结构·算法·链表
你可以自己看38 分钟前
python中函数式编程与高阶函数,装饰器与生成器,异常处理与日志记录以及项目实战
服务器·开发语言·python
gopher95111 小时前
go语言 数组和切片
开发语言·golang
ymchuangke1 小时前
线性规划------ + 案例 + Python源码求解(见文中)
开发语言·python
gopher95111 小时前
go语言Map详解
开发语言·golang
鸠摩智首席音效师1 小时前
如何设置 Django 错误邮件通知 ?
python·django