0

i'm try to create dateframe table in docx file. How i can do it? Me need table like:

enter image description here

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()

enter image description here

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')

enter image description here

kirastel
  • 39
  • 5
  • 1
    Does this answer your question? [Writing a Python Pandas DataFrame to Word document](https://stackoverflow.com/questions/40596518/writing-a-python-pandas-dataframe-to-word-document) – Panagiotis Kanavos Apr 13 '22 at 15:31
  • Have you tried anything? I found the duplicate by googling for `pandas docx`. All Excel formats are ZIP files containing well-defined XML documents. In the worst case you could create the XML files yourelf but there are several libraries that allow creating xlsx or docx documents. – Panagiotis Kanavos Apr 13 '22 at 15:31
  • I'm try method from answers https://stackoverflow.com/questions/40596518/writing-a-python-pandas-dataframe-to-word-document , but it's save only data without tittles 'Year', 'Factor' – kirastel Apr 13 '22 at 15:38
  • We can't guess what you actually did. You didn't post any code or results. Obviously you already found the answer to this question - how to generate a Word document. Your actual problem is how to add headers to a table – Panagiotis Kanavos Apr 13 '22 at 15:41

1 Answers1

0

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")