【问题标题】:Importing table that was created in python to docx将在 python 中创建的表导入到 docx
【发布时间】:2019-05-16 19:55:27
【问题描述】:

我在python中创建了一个表,但是我无法将该表导入docx,我该怎么办?

import docx 
import pandas as pd 
doc = docx.Document('Demo.docx')   

raw_data = {"Density" : [147.7, 148.6, 149.3, 153.3, 147.3, 147.8, 149.4, 147.8, 151.1, 148.5 ],
            "% Compaction":[95.4, 96.0, 95.3, 98.6, 95.1, 95.5, 96.4, 95.5, 97.5, 95.9],
            "Pass/Fail":["Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass",]} 
df = pd.DataFrame(raw_data, columns= ['Density','% Compaction','Pass/Fail']) 
print(df)

docx.tables = df 
doc.save("Demo.docx")

【问题讨论】:

  • 你也许可以使用 json.dumps() 我不太确定你想要什么虽然 docx.tables 变成一个 doc 文件?
  • 这里有一些观察:您正在覆盖包docx.tables = ...。你的意思是doc.tables = ??此外,如果不查看文档,我怀疑您不能只将 single table instance 写入文档的 tables 集合。可能有一个tables.add 方法或table 类,您可以对其进行实例化然后添加到集合中。

标签: python pandas dataframe docx python-3.7


【解决方案1】:

假设您要将数据转储到 csv 文件而不是 docx 中(为什么是 MS Word 文档...?)

我对这个问题的解决方案是像您一样使用 pandas 的 Dataframe,但稍作修改:

import pandas as pd

raw_data = {"Density" : [147.7, 148.6, 149.3, 153.3, 147.3, 147.8, 149.4, 147.8, 151.1, 148.5 ], "% Compaction":[95.4, 96.0, 95.3, 98.6, 95.1, 95.5, 96.4, 95.5, 97.5, 95.9], "Pass/Fail":["Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass","Pass",]}
csv_file = "test_data.csv" #name of the file
df=pd.DataFrame(raw_data) #using pandas' Dataframe
df.to_csv(csv_file, index = False) #dumping data with headers, but without indexing 

我希望这会有所帮助! :)

【讨论】:

  • 可能他们正在 Word 文档中构建表格,因为他们需要 Word 文档。您的答案可以转储到 CSV,但没有理由假设这就是 OP 想要的:)
【解决方案2】:

document 对象支持add_table 方法,该方法在文档中创建表格占位符。

您的赋值语句非常错误,您正在覆盖包 (docx.tables)。即使允许拼写错误,doc.tables 是表 collection,因此您正在使用 pandas DataFrame 覆盖它!

您需要使用doc.add_table 方法创建一个表格,然后用数据框中的值填充其单元格。

Table 对象没有构造函数。它只是通过add_table 方法添加到文档中。

未经测试,但类似这样:

table = doc.add_table(rows=1, cols=len(df.columns))
hdr_cells = table.rows[0].cells
for i,cl in enumerate(hdr_cells):
    hdr_cells[i].text = df.columns[i]

for row in df.index:
    values = df.loc[row]
    row_cells = table.add_row().cells
    for i,v in enumerate(values):
        row_cells[i].text = v

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多