将Python Pandas DataFrame写入Word文档

spr*_*ore 16 python dataframe pandas

我正在创建一个使用Pandas DataFrames的Python生成的报告.目前我正在使用该DataFrame.to_string()方法.但是,这会将该文件写为字符串.有没有办法让我实现这一点,同时保持它作为一个表,所以我可以使用表格格式.

码:

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()
Run Code Online (Sandbox Code Playgroud)

当前打印输出(作为字符串):

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...
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 23

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

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

conda install python-docx --channel conda-forge
Run Code Online (Sandbox Code Playgroud)

或者从命令行pip install:

pip install python-docx
Run Code Online (Sandbox Code Playgroud)

安装完成后,我们可以使用它打开文件,添加表格,然后用数据框数据填充表格的单元格文本.

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')
Run Code Online (Sandbox Code Playgroud)

  • 如果您要创建新文档,请使用“doc = docx.Document()”而不是“doc = docx.Document('./test.docx')”。否则你会得到一个 PackageNotFoundError 错误。 (3认同)
  • 有没有办法在表格周围添加边框?该代码有效,但我认为我的报告在写入我的 Word 文档的 Pandas Dataframe 周围有边框看起来会更好。谢谢!:) (2认同)
  • @HenryHub设置表格的[样式](http://python-docx.readthedocs.io/en/latest/user/styles-using.html),例如,'t.style ='Table Grid'' (2认同)

Ted*_*nec 6

def doctable(data, tabletitle, pathfile):
    from docx import Document
    from docx.shared import Pt, Mm
    import pandas as pd
    document = Document()
    section = document.sections[0]
    section.page_height = Mm(297)
    section.page_width = Mm(210)
    section.left_margin = Mm(20)
    section.right_margin = Mm(20)
    section.top_margin = Mm(20)
    section.bottom_margin = Mm(20)
    section.header_distance = Mm(12.7)
    section.footer_distance = Mm(12.7)
    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!
    table.allow_autofit = True
    table.autofit = True
    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)
    return 0
Run Code Online (Sandbox Code Playgroud)