python批量处理word中的表格

def word_table_formater():
    from win32com import client

    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open('C:\\Users\\Administrator\\Desktop\\test.docx')

    i = 1
    for table in doc.Tables:
        print(i, len(doc.Tables))
        # 设置列宽
        table.Columns(1).Width = 85
        table.Columns(2).Width = 85
        table.Columns(3).Width = 28
        table.Columns(4).Width = 28
        table.Columns(5).Width = 28
        table.Columns(6).Width = 155
        table.Range.ParagraphFormat.Alignment = 1  # 水平居中
        table.Range.Cells.VerticalAlignment = 1  # 垂直居中
        for cell in table.Range.Cells:
            # 这个操作比较耗时
            cell.TopPadding = 0.3  # 单元格上边距
            cell.BottomPadding = 0.3
            cell.LeftPadding = 0.3
            cell.RightPadding = 0.3
        i += 1
            
    doc.Save()
    doc.Close()


com对象属性和方法:
ParagraphFormat 对象

posted @ 2024-06-27 11:12  猫种鱼  阅读(40)  评论(0)    收藏  举报