Python 将数据帧数据写入现有.docx文档表的快速方法

Python 将数据帧数据写入现有.docx文档表的快速方法,python,pandas,ms-word,docx,python-docx,Python,Pandas,Ms Word,Docx,Python Docx,我需要将dataframe数据写入Word文档中的现有表。文档中的表已经有两行了,我需要在这两行之后添加df行。使用pythondocx库 document = Document(docx=document_name) table = document.tables[0] for i in range(orders.shape[0]): table.add_row() for i in range(orders.shape[0]): for j in range(orders.s

我需要将dataframe数据写入Word文档中的现有表。文档中的表已经有两行了,我需要在这两行之后添加df行。使用
pythondocx

document = Document(docx=document_name)
table = document.tables[0]
for i in range(orders.shape[0]):
    table.add_row()
for i in range(orders.shape[0]):
    for j in range(orders.shape[1]):
        table.cell(i + 2, j).text = str(orders.values[i,j]) 
document.save('xxx.docx')

这个脚本运行得很好,但是它花费了很长的时间:它需要10秒来写一行。如果dataframe有5000行,那就是一个问题。有人知道更快的方法吗?

从避免重复的行和列查找开始,如下所示:

values = orders.values
for i in range(orders.shape[0]):
    row = table.add_row()
    for j, cell in enumerate(row.cells):
        cell.text = str(values[i, j]) 

看看你能有多大的进步。

像x10一样更快。但仍然很慢:)你收集了什么时间数据?下一步是一次性创建表,而不是添加行。这意味着您需要自己创建前两行,而不是扩展现有表。