word表批量处理小技巧(python+宏)

1.选择所有的表

Sub SelectAllTables()

Dim tempTable As Table

Application.ScreenUpdating = False

'判断文档是否被保护
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
    MsgBox "文档已保护,此时不能选中多个表格!"
    Exit Sub
End If
'删除所有可编辑的区域
ActiveDocument.DeleteAllEditableRanges wdEditorEveryone
'添加可编辑区域
For Each tempTable In ActiveDocument.Tables
    tempTable.Range.Editors.Add wdEditorEveryone
Next
'选中所有可编辑区域
ActiveDocument.SelectAllEditableRanges wdEditorEveryone
'删除所有可编辑的区域
ActiveDocument.DeleteAllEditableRanges wdEditorEveryone

Application.ScreenUpdating = True

End Sub
上面代码用于选择word中所有表当我们运行完上面的宏后,我们所有打开的word中表已被选择,选中后可以改变表的统一所有表的样式

2.所表设置内容自适应

Sub SelectAllTables()
Application.Browser.Target = wdBrowseTable

For i = 1 To ActiveDocument.Tables.Count

ActiveDocument.Tables(i).AutoFitBehavior (wdAutoFitContent) '根据内容自动调整表格

ActiveDocument.Tables(i).AutoFitBehavior (wdAutoFitWindow) '根据窗口自动调整表格

ActiveDocument.Tables(i).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter '水平居中

ActiveDocument.Tables(i).Range.ParagraphFormat.Alignment = wdCellAlignVerticalCenter '垂直居中
Next i

3.末行合并自动分类填充

def word1():
# 打开word文档
word = win32com.client.Dispatch(‘Word.Application’)
path = “D:\work\cs\测试记录.docx”
doc = word.Documents.Open(FileName=path, Encoding=‘gbk’)
for table in doc.Tables:

    youxiao=[0,1,2,3,4,5]
    youxiao.append(len(table.rows)-1)
    youxiao.append(len(table.rows)-2)
    istabl=True
    for index,row in enumerate( table.Rows):
        changdu=len(row.Cells)
        if(index  in youxiao):
            # print(index)
            word.Selection.SetRange(table.Cell(index+1,changdu-1).Range.Start, table.Cell(index+1,changdu).Range.End)
            word.Selection.Cells.Merge()
        else:
            if(istabl):
                table.Cell(index+1, changdu).Range.Text = "实际执行结果"
                istabl=False
            else:
                table.Cell(index + 1, changdu).Range.Text = "通过"
    # table.AutoFitBehavior(wdAutoFitContent)
path = "D:\\work\\cs\\新建 Microsoft Word 文档4.docx"
doc.SaveAs(path)
doc.Close()
word.Quit()

4.统一加列

path=“D:\work\cs\新建 Microsoft Word 文档.docx”
doc =Document(path)
for table in doc.tables:
table.add_column(Cm(20))
doc.save(“D:\work\cs\新建 Microsoft Word 文档1.docx”)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值