将Python Pandas DataFrame写入Word文档 [英] Writing a Python Pandas DataFrame to Word document

查看:1978
本文介绍了将Python Pandas DataFrame写入Word文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用Pandas DataFrames生成的Python报表.当前,我正在使用DataFrame.to_string()方法.但是,这会以字符串形式写入文件.在将其保留为表格的同时,有什么方法可以实现这一点,以便我可以使用表格格式.

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.

代码:

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...

推荐答案

您可以使用python-docx库将表直接写入.docx文件.

You can write the table straight into a .docx file using the python-docx library.

如果您使用的是Conda或使用Anaconda安装的Python,则可以从命令行运行命令:

If you are using the Conda or installed Python using Anaconda, you can run the command from the command line:

conda install python-docx --channel conda-forge

或通过命令行进行pip安装:

Or to pip install from the command line:

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')

这篇关于将Python Pandas DataFrame写入Word文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆