我目前正在编写一个脚本,需要写入 .docx 文件以进行演示。我使用 pandas 来处理脚本中的所有数据计算。我希望使用 PyWIN32 将 pandas 数据帧写入 word.docx 文件中书签处的表中。数据框由浮点数组成。伪代码是这样的。
frame = DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])
随着pywin32导入...
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
rng.InsertTable.here
现在我想在此书签处创建一个表。表的尺寸应由数据框决定。我还希望列标题成为 Word 表格中的标题。
基本上,您需要做的就是在 Word 中创建一个表格,并从数据框的相应值填充每个单元格的值
# data frame
df= DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
# creating Table
# add one more row in table at word because you want to add column names as header
Table=rng.Tables.Add(rng,NumRows=df.shape[0]+1,NumColumns=df.shape[1])
for col in range(df.shape[1]):
# Writing column names
Table.Cell(1,col+1).Range.Text=str(df.columns[col])
for row in range(df.shape[0]):
# writing each value of data frame
Table.Cell(row+1+1,col+1).Range.Text=str(df.iloc[row,col])
请注意Table.Cell(row+1+1,col+1)
这里已经添加了两个。原因是因为 Microsoft Word 中的 Table 从 1 开始索引。因此,row 和 col 都必须加 1,因为 pandas 中的数据帧索引是从 0 开始的。
在行处添加另一个 1,为数据框列作为标题提供空间。应该这样做!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)