首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Python Pandas DataFrame写入Word文档

将Python Pandas DataFrame写入Word文档
EN

Stack Overflow用户
提问于 2016-11-15 03:37:53
回答 3查看 35.6K关注 0票数 22

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

代码:

代码语言:javascript
复制
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()

当前打印输出(字符串形式):

代码语言:javascript
复制
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...
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-11-15 04:56:48

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

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

代码语言:javascript
复制
conda install python-docx --channel conda-forge

或者从命令行执行pip install:

代码语言:javascript
复制
pip install python-docx

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

代码语言:javascript
复制
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')
票数 44
EN

Stack Overflow用户

发布于 2018-12-08 21:24:29

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2021-12-08 21:37:57

如果你愿意,可以用这个来证明它:

代码语言:javascript
复制
from docx import Document
import pandas as pd

def df_to_word(data: dict, report_name:str) -> docx.Document:
    assert type(data) == dict, 'data has to be dict'
    assert '.docx' in report_name, 'report_name has to be a .docx file'
    df = pd.DataFrame(data)
    doc = docx.Document()

    table = doc.add_table(df.shape[0]+1, df.shape[1])

    for j in range(df.shape[-1]):
        table.cell(0,j).text = df.columns[j]

    for i in range(df.shape[0]):
        for j in range(df.shape[-1]):
            table.cell(i+1,j).text = str(df.values[i,j])

    doc.save(f'./{report_name}')


data = {
  "calorierbes": [420, 380, 390],
  "duratierbn": [50, 40, 45],
  "durationverg": [50, 40, 45],
  "duratiorgern": [50, 40, 45],
  "calorieers": [420, 380, 390],
  "calorierbers": [420, 380, 390],
  "calorierbes": [420, 380, 390]
}
df_to_word(data, 'report_4.docx')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40596518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档