【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()
相关推荐
SelectDB技术团队3 分钟前
丰巢日志平台 ELK 替代:Apache Doris / SelectDB 的技术能力与实践
开发语言·python
BetterFlow_CFD3 分钟前
COMSOL声学仿真基础知识(二)
开发语言·算法·matlab
麻瓜老宋7 分钟前
AI开发C语言应用按步走,表达式计算器calc的第十九步,注释、表达式分隔符、long double 精度
c语言·开发语言·atomcode
崖边看雾7 分钟前
Python学习——函数
开发语言·windows·python·学习·pycharm
深念Y20 分钟前
Windows幽灵端口占用:HNS如何无声偷走你的端口
windows·python·bug·环境·端口·特权
宸津-代码粉碎机21 分钟前
Jar热部署进阶实战|修复原生方案OOM与类冲突问题,生产级无BUG优化方案
java·大数据·服务器·开发语言·前端·人工智能·python
咖啡星人k31 分钟前
AI 编程工具集体变脸:Cursor 漏洞、TRAE 限额、Claude Code 数据收集风波
人工智能·安全·microsoft·cursor·trae·ai编程工具
未知违规用户2 小时前
大模型项目:RAG项目实战与FlagEmbedding模型
人工智能·windows·python·深度学习
IT小盘9 小时前
03-大模型API不只是发送Prompt-流式输出超时重试与异常处理
人工智能·python·prompt
Zzz不能停10 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试