在python中使用win32打开的word文档中复制表

2024-04-24 09:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用Win32打开了一个MS Word文档,我想复制Word文档中间的某个表。


Tags: 文档wordmswin32
1条回答
网友
1楼 · 发布于 2024-04-24 09:45:58

您可以通过win32com控制单词表

import win32com.client as win32
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
doc = word.Documents.Open('your file path')

您可以检查文档中的表格编号:

doc.Tables.Count

注意:与python不同,单词索引从1开始

可以通过以下方式遍历表:

table = doc.Tables(1)       #You can choose the table you need
for row in range(1,table.Rows.Count + 1):
    for col in range(1,table.Columns.Count + 1):
        print(table.Cell(Row = row,Column = col).Range.Text)

这样,就实现了获取表格内容的功能。当然,如果要将此表的内容重新复制到另一个表,可以重新创建一个表并将其添加到Word文档中

以下是完整的示例:

import win32com.client as win32
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
doc = word.Documents.Open('test.docx')

tableNum = doc.Tables.Count     #the table numbers 

print(doc.Tables.Count)

location = doc.Range()
location.Move() # place table at the end 
table = doc.Tables(1)       #You can choose the table you need
table2 = doc.Content.Tables.Add(location, table.Rows.Count, table.Columns.Count)
table2.AutoFormat(36)

for row in range(1,table.Rows.Count + 1):
    for col in range(1,table.Columns.Count + 1):
        print(table.Cell(Row = row,Column = col).Range.Text)
        table2.Cell(Row = row,Column = col).Range.Text = table.Cell(Row = row,Column = col).Range.Text

doc.Close()     #Don't forget to close the document
word.Quit()

这是我的test.docx:

enter image description here

当我运行程序时,它对我有效:

enter image description here

相关问题 更多 >