【问题标题】:Writing a pandas dataframe to a word document table via pywin32通过 pywin32 将 pandas 数据框写入 word 文档表
【发布时间】:2015-07-22 03:08:09
【问题描述】:

我目前正在编写一个脚本,该脚本需要写入 .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 表中的标题。

【问题讨论】:

  • 虽然这并不是您问题的直接答案,但您可能需要考虑导出到 Excel 电子表格(pandas DataFrames 有一个 to_excel() 函数)并将生成的表格插入到您的文档中。
  • 你可能无法自动化整个过程(我对 PyWin32 完全不熟悉),但这是使用 Windows 和 GUI 应用程序的代价。
  • 在使用 pywin32 时值得注意的是,在许多情况下,它不会让您将超过 2GB 的数据加载到内存中,这在使用 pandas 时有时会出现问题。这是因为它在 windows 中是一个 32 位进程,而这类进程通常默认限制为 2GB。

标签: python pandas ms-word python-3.4 pywin32


【解决方案1】:

基本上,您需要做的就是在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,以便为数据框列提供空间作为标题。应该这样做!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多