python-3.x - 从 csv 文件向 python-docx 添加表非常慢
问题描述
我必须在 docx word 文档中从 CSV 文件中添加一个大约 1500 行和 9 列(75 页)的表格。使用 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])
推荐阅读
- jenkins - Jenkins Kubernetes Plugin PodTemplate 无法将工作空间从 master 映射到 pod,而是在管道中工作
- c++ - 在这种情况下对象是否被破坏?
- mysql-python - 在 python 中加载 mysqlsh 模块
- c# - Visual Studio c# winform 打开链接
- typescript - AWS CDK 管道构造:代码构建错误 254
- spring - 使用不同的配置 Spring Boot 减少我的内存占用
- click - 赛普拉斯 - 只有当它是可点击的元素时才点击它
- python - 在python中访问嵌套字典值
- oracle - REST 服务安装期间的 Oracle 数据库错误:PLS-00201:必须声明标识符“ORDS.ENABLE_SCHEMA”
- javascript - Axios Promise 结果未复制到本地函数变量/本地状态