slaon的个人博客分享 http://blog.sciencenet.cn/u/slaon

博文

[转载]python docx 加速创建大型表格

已有 1289 次阅读 2022-6-5 00:00 |系统分类:科研笔记|文章来源:转载

参考link

小型表格

import docx
import pandas as pd
data = pd.read_excel("some_data.xlsx")
doc = docx.Document() 
table = doc.add_table(rows=data.shape[0], cols=data.shape[1])
for i in range(df.shape[0]):
    for j in range(df.shape[1]):
        table.cell(i,j).text = str(df.values[i,j])
doc.save("output_file_path.docx")

大型表格,使用 table_cells = table._cells将所有单元格抽取出来,

在对抽取出来的单元格单独处理,避免对表格循环

import docx
import pandas as pd
data = pd.read_excel("some_bigger_data.xlsx")
doc = docx.Document() 
table = doc.add_table(rows=data.shape[0], cols=data.shape[1])
table_cells = table._cells
for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        table_cells[j + i * data.shape[1]].text =  str(data.values[i][j])
doc.save("output_file_path.docx")


https://wap.sciencenet.cn/blog-531760-1341572.html

上一篇:[转载]Windows强制停止进程
下一篇:[转载]python docx创建题注并交叉引用(WPS可用)
收藏 IP: 112.32.22.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-29 01:04

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部