2015-07-22 45 views
1

我目前正在研究一个需要写入一个.docx文件用于演示目的的脚本。我使用熊猫来处理脚本中的所有数据计算。我正在寻找使用PyWIN32在word.docx文件的书签中将一个熊猫数据框写入表中。数据帧由浮点组成。伪代码是这样的。通过pywin32将一个熊猫数据框写入一个word文档表

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表格中的标题。

+1

虽然这不是直接回答您的问题,但您可能需要考虑导出为Excel电子表格(pandas DataFrames有一个[to_excel()](http://pandas.pydata.org/pandas-docs /stable/generated/pandas.DataFrame.to_excel.html)函数)并将结果表插入到文档中。 – brenns10

+0

你可能无法自动化整个过程(我完全不熟悉PyWin32),但这是使用Windows和GUI应用程序的代价。 – brenns10

+1

使用pywin32时值得注意的是,在许多情况下,它不会让您将超过2GB的数据加载到内存中,这在使用熊猫时有时会出现问题。这是因为它是一个32位的Windows进程,默认情况下这些进程通常限制为2GB。 – firelynx

回答

3

基本上,所有你需要做的是在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中的表从1开始索引。所以,行和列必须加1,因为熊猫中的数据帧索引从0开始。

另一个1在行上添加以为数据帧提供空间列作为标题。这应该做到这一点!

相关问题