【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()
相关推荐
潇潇云起2 分钟前
mapdb
java·开发语言·数据结构·db
prettyxian5 分钟前
【QT】信号与槽基础:手动连接的原理与实践
开发语言·qt
傻乐u兔7 分钟前
C语言初阶————结构体
c语言·开发语言
weixin_445054727 分钟前
力扣热题52
开发语言·python
mengyoufengyu7 分钟前
JupyterLab4.5安装使用
python·jupyter·jupyterlab
weixin_462446238 分钟前
Python 使用阿里云 STS 获取临时访问凭证并上传文件至 OSS:Flask API 实现
python·阿里云·flask
逑之10 分钟前
C语言笔记2:C语言数据类型和变量
c语言·开发语言·笔记
何中应11 分钟前
@Autowrited和@Resource注解的区别及使用场景
java·开发语言·spring boot·后端·spring
源代码•宸12 分钟前
Golang语法进阶(Context)
开发语言·后端·算法·golang·context·withvalue·withcancel
一条咸鱼_SaltyFish12 分钟前
[Day16] Bug 排查记录:若依框架二次开发中的经验与教训 contract-security-ruoyi
java·开发语言·经验分享·微服务·架构·bug·开源软件