【发布时间】:2018-05-16 16:42:38
【问题描述】:
有人可以举例说明我们如何在不丢失格式的情况下将数据透视表输出从 pandas 发送到 word 文档。
【问题讨论】:
-
stackoverflow.com/questions/40596518/…,也许这对你有帮助。
标签: python python-2.7 pandas ms-word pivot-table
有人可以举例说明我们如何在不丢失格式的情况下将数据透视表输出从 pandas 发送到 word 文档。
【问题讨论】:
标签: python python-2.7 pandas ms-word pivot-table
从命令行进行 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')
【讨论】:
我建议使用pandas.to_csv()将其导出为csv,然后读取csv以在word文档中创建表格。
【讨论】:
csv在word文档中创建table”?