如何将pandas数据透视表打印到word文档

时间:2018-05-16 16:42:39

标签: python python-2.7 pandas ms-word pivot-table

有人可以解释一下我们如何将pandas的数据透视表输出发送到word文档而不会丢失格式。

2 个答案:

答案 0 :(得分:0)

我建议使用pandas.to_csv()将其导出到csv,然后阅读csv以在word文档中创建表。

答案 1 :(得分:0)

从命令行进行pip安装:

pip install python-docx

安装完成后,我们可以使用它来打开文件,添加表,然后使用数据框架数据填充表的单元格文本。

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

从这里的答案: Writing a Python Pandas DataFrame to Word document