Python 如何将数据透视表打印到word文档
有人可以举例说明如何将pandas的数据透视表输出发送到word文档而不丢失格式。我建议使用pandas.to_csv()将其导出到csv,然后读取csv以在word文档中创建表。从命令行执行pip安装:Python 如何将数据透视表打印到word文档,python,python-2.7,pandas,ms-word,pivot-table,Python,Python 2.7,Pandas,Ms Word,Pivot Table,有人可以举例说明如何将pandas的数据透视表输出发送到word文档而不丢失格式。我建议使用pandas.to_csv()将其导出到csv,然后读取csv以在word文档中创建表。从命令行执行pip安装: pip install python-docx 安装后,我们可以使用它打开文件,添加表,然后用数据框数据填充表的单元格文本 import docx import pandas as pd # i am not sure how you are getting your data, but
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')
答案如下:
如何建议“阅读csv
在word文档中创建表”
,也许这可以帮助您。