将 Python Pandas DataFrame 写入 Word 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40596518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a Python Pandas DataFrame to Word document
提问by spriore
I'm working on creating a Python generated report that uses Pandas DataFrames. Currently I am using the DataFrame.to_string()
method. However this writes to the file as a string. Is there a way for me to achieve this while keeping it as a table so I can use table formating.
我正在创建一个使用 Pandas DataFrames 的 Python 生成的报告。目前我正在使用该DataFrame.to_string()
方法。但是,这将作为字符串写入文件。有没有办法让我在将其保留为表格的同时实现这一点,以便我可以使用表格格式。
Code:
代码:
SEMorgkeys = client.domain_organic(url, database = "us", display_limit = 10, export_columns=["Ph,Pp,Pd,Nq,Cp,Ur,Tr"])
org_df = pd.DataFrame(SEMorgkeys)
f = open(name, 'w')
f.write("\nOrganic:\n")
f.write(org_df.to_string(index=False,justify="left"))
f.close()
Current Printout (as string):
当前打印输出(作为字符串):
CPC Keyword Position Difference Previous Position Search Volume Traffic (%) Url
75.92 small business factoring 0 1 210 11.69 https://www..com/small-business-f...
80.19 factoring company 0 8 1600 5.72 https://www..com/factoring-vs-ban...
回答by James
You can write the table straight into a .docx
file using the python-docx
library.
您可以.docx
使用python-docx
库将表直接写入文件。
If you are using the Conda or installed Python using Anaconda, you can run the command from the command line:
如果您正在使用 Conda 或使用 Anaconda 安装 Python,您可以从命令行运行命令:
conda install python-docx --channel conda-forge
Or to pip install from the command line:
或者从命令行 pip install:
pip install python-docx
After that is installed, we can use it to open the file, add a table, and then populate the table's cell text with the data frame data.
安装完成后,我们可以使用它打开文件,添加表格,然后用数据框数据填充表格的单元格文本。
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')
回答by Tedo Vrbanec
def doctable(data, tabletitle, pathfile):
from docx import Document
import pandas as pd
document = Document()
data = pd.DataFrame(data) # My input data is in the 2D list form
document.add_heading(tabletitle)
table = document.add_table(rows=(data.shape[0]), cols=data.shape[1]) # First row are table headers!
for i, column in enumerate(data) :
for row in range(data.shape[0]) :
table.cell(row, i).text = str(data[column][row])
document.save(pathfile)