'Pandas Dateframe to docx
i'm try to create dateframe table in docx file. How i can do it? Me need table like:
My dateframe:
colums_6 = pd.MultiIndex.from_product([['6'], years_list],
names=['Factor', 'Year'])
df_6 = pd.DataFrame([factor_6], index=['World'], columns=colums_6)
values_list = df_6.values.tolist()
I used this method, but it does not create the full table that I need:
doc = docx.Document()
# extra row is so we can add the header row
t = doc.add_table(report_doc.shape[0]+1, report_doc.shape[1])
# add the header rows.
for j in range(report_doc.shape[-1]):
t.cell(0,j).text = report_doc.columns[j]
# add the rest of the data frame
for i in range(report_doc.shape[0]):
for j in range(report_doc.shape[-1]):
t.cell(i+1, j).text = str(report_doc.values[i, j])
doc.save('report.docx')
Solution 1:[1]
You could save your dataframe to excel using pandas.DataFrame.to_excel and then copy-paste the table into Word.
In your case, that would be:
df_6.to_excel("output.xlsx")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Justin Schmidt |



