繁体   English   中英

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

[英]Duplicating a table in word document opened using win32 in python

我在 python 中使用 win32 打开了一个 ms-word 文档,我想复制一个位于 word 文档中间某处的表格。

您可以通过win32com控制Word表格。

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)

这样就实现了获取表格内容的function。 当然,如果你想把这个表的内容重新复制到另一个表中,你可以重新创建一个表并添加到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:

在此处输入图像描述

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

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM