Skip to content Skip to sidebar Skip to footer

Writing A Pandas Dataframe To A Word Document Table Via Pywin32

I am currently working on a script that needs to write to a .docx file for presentation purposes. I use pandas to handle all my data calculations in the script. I am looking to w

Solution 1:

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 
# addone more rowintableat word because you want toaddcolumn names as header
Table=rng.Tables.Add(rng,NumRows=df.shape[0]+1,NumColumns=df.shape[1])

for col inrange(df.shape[1]):        
    # Writing column names 
    Table.Cell(1,col+1).Range.Text=str(df.columns[col]) 
    forrowinrange(df.shape[0]):
        # writing eachvalueof 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 !

Post a Comment for "Writing A Pandas Dataframe To A Word Document Table Via Pywin32"