从 csv 文件添加表到 python-docx 非常慢

Kar*_*ete 6 python-3.x python-docx

我必须从 CSV 文件中添加一个大约 1500 行和 9 列(75 页)的表格到 docx word 文档中。使用 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')
Run Code Online (Sandbox Code Playgroud)

提前致谢

小智 5

每次访问 python-docx 的“cells”属性时,都会遍历整个表。
所以你最好尽可能少地调用“.cell”并使用单元格缓存。
这是访问大小为 3*1500 的表的两个示例:

代码1:约150.0s

for row in table.rows:
    print('processing: {0:30s}'.format(row.cells[0].text),end='\r')
Run Code Online (Sandbox Code Playgroud)

代码2:约1.4s

clls=table._cells
for row_idx in range(len(clls)//table._column_count):
    print('processing: {0:30s}'.format( 
       clls[0 + row_idx*table._column_count].text),end='\r')
Run Code Online (Sandbox Code Playgroud)

clls=table._cells在代码 2 中,使用“_cells”来处理单元格合并,因此ccls[column_idx + row_idx*table._column_count].text与 一样好table.rows[row_idx].cells[column_idx].text,并且不需要table完全是矩形


sca*_*nny 4

您需要尽量减少对 的调用次数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])
Run Code Online (Sandbox Code Playgroud)