Could some one please explain with an example about how we can send the pivot table output from pandas to word document without losing format.
Asked
Active
Viewed 2,887 times
1
-
https://stackoverflow.com/questions/40596518/writing-a-python-pandas-dataframe-to-word-document?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa, maybe this can help you. – Lambda May 17 '18 at 02:18
2 Answers
1
to pip install from the command line:
pip install python-docx
After that is installed, we can use it to open the file, add a table, and then populate the table's cell text with the data frame data.
import docx
import pandas as pd
# i am not sure how you are getting your data, but you said it is a
# pandas data frame
df = pd.DataFrame(data)
# open an existing document
doc = docx.Document('./test.docx')
# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = doc.add_table(df.shape[0]+1, df.shape[1])
# add the header rows.
for j in range(df.shape[-1]):
t.cell(0,j).text = df.columns[j]
# add the rest of the data frame
for i in range(df.shape[0]):
for j in range(df.shape[-1]):
t.cell(i+1,j).text = str(df.values[i,j])
# save the doc
doc.save('./test.docx')
From the answer here at: Writing a Python Pandas DataFrame to Word document

sudoCoder
- 115
- 2
- 13
-1
I suggest exporting it to csv using pandas.to_csv()
, and then read the csv to create a table in a word document.
-
how to do suggest to "read the `csv` to create a `table` in a word document"? – akshat May 16 '18 at 18:22