将在python中创建的表导入到docx

时间:2019-05-16 19:55:28

标签: python pandas dataframe docx python-3.7

我已经在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")

2 个答案:

答案 0 :(得分:0)

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

我要解决此问题的方法是像您一样使用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 

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

答案 1 :(得分:0)

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