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

在python中使用win32打开的word文档中复制表,python,ms-word,Python,Ms Word,我在Python中使用Win32打开了一个MS Word文档,我想复制Word文档中间的某个表。 可以通过Win32 com。 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中使用Win32打开了一个MS Word文档,我想复制Word文档中间的某个表。

可以通过Win32 com。
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:

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


“COM索引从1开始”-COM使用
SAFEARRAY
允许任意索引,由
SAFEARRAYBOUND
字段控制。Word可能已选择1作为下限,但这与COM无关。谢谢您的评论。但表格位于Word文档的中间。例如,Word文档有10页。前几页有一些文本,然后有一个表格1,现在我想复制此表格1;然后把新桌子放在桌子1后面。新创建的表应具有相同的字体类型和字体大小。@pravinshinde此函数基于文档中要选择的表的数量,而不考虑文本。文本的样式可以根据您的需要进行更改。谢谢。您知道如何对齐表格单元格中的文本吗