Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数据透视表打印到word文档_Python_Python 2.7_Pandas_Ms Word_Pivot Table - Fatal编程技术网

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

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

有人可以举例说明如何将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 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文档中创建
表”
,也许这可以帮助您。