Writing a pandas dataframe to a word document table via pywin32

大城市里の小女人 提交于 2019-12-04 19:30:25

Basically, all you need to do is create a table in word and populate the values of each cell from the corresponding values of data frame

# 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])  

Notice that Table.Cell(row+1+1,col+1) has been added two ones here. The reason is because Table in Microsoft Word start indexing from 1. So, both row and col has to be added 1 because data frame indexing in pandas start from 0.

Another 1 is added at row to give space for data frame columns as headers. That should do it !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!