【问题标题】:How can I print pandas pivot table to word document如何将熊猫数据透视表打印到 Word 文档
【发布时间】:2018-05-16 16:42:38
【问题描述】:

有人可以举例说明我们如何在不丢失格式的情况下将数据透视表输出从 pandas 发送到 word 文档。

【问题讨论】:

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


【解决方案1】:

从命令行进行 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如何建议“阅读csv在word文档中创建table”?
    猜你喜欢
    • 2019-04-28
    • 2021-02-28
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多