python-3.x - 从 csv 文件向 python-docx 添加表的速度非常慢

标签 python-3.x python-docx

我必须在 docx word 文档中从大约 1500 行和 9 列(75 页)的 CSV 文件中添加一个表格。使用 python-docx。
我尝试了不同的方法,用 Pandas 读取 csv 或直接打开 de csv 文件,按照我选择的方式独立完成工作大约需要 150 分钟
我的问题是这是否可能是正常行为,或者是否存在任何其他方式来改进此任务。
我正在使用这个 for 循环来读取几个 cvs 文件并以表格格式解析它

        for toTAB in listBRUTO:
            df= pd.read_csv(toTAB)
            
            # 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])
            t.style = 'LightShading-Accent1' # border
           
        
            # 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])
            
            #TABLE Format
            for row in t.rows:
                for cell in row.cells:
                    paragraphs = cell.paragraphs
                    for paragraph in paragraphs:
                        for run in paragraph.runs:
                            font = run.font
                            font.name = 'Calibri'
                            font.size= Pt(7)

            
            doc.add_page_break()
        doc.save('blabla.docx')
提前致谢

最佳答案

您需要尽量减少对 table.cell() 的调用次数。 .由于单元格合并的工作方式,这些昂贵的操作在紧密循环中执行时确实会增加。
我将从重构这个块开始,看看会产生多少改进:

# --- add the rest of the data frame ---
for i in range(df.shape[0]):
    for j, cell in enumerate(table.rows[i + 1].cells):
        cell.text = str(df.values[i, j])

关于python-3.x - 从 csv 文件向 python-docx 添加表的速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62268813/

相关文章:

python - 清除win7中的python IDLE屏幕

python - 使用Python连接Docker容器中的MySQL

python - 什么样的对象可以作为 Spark RDD 中的元素?

python - 如何在python docx模板(docxtpl)中显示图像? python

python - 在文档的页面上查找单词

Python:使用 python-docx/lxml 创建一个 "Table Of Contents"

python - 如何使用python-docx将分数输入到WORD文档中

python - 如何在pygame中获取屏幕外的像素颜色?

python - 在 Python 3 中从 utf-16 转换为 utf-8

python - 为什么我的 IDE 无法自动完成 python-docx?