如何使用Python在word文档中创建表格

如何使用Python在word文档中创建表格

  • 介绍
  • 效果
  • 代码

介绍

本文将介绍如何使用Python库python-docx在Word文档中创建表格。

效果

插入表格前的word文档:

插入表格后的word文档:

代码

python 复制代码
from docx import Document

# 加载现有的Word文档
doc = Document(r'C:\Users\Administrator\Desktop\Word文档\example.docx')

# 添加一个表格,3行4列
table = doc.add_table(rows=3, cols=4)

# 设置表格样式(可选)
table.style = 'Table Grid'

# 填充表格数据
data = [
    ["Header1", "Header2", "Header3", "Header4"],
    ["Row1 Col1", "Row1 Col2", "Row1 Col3", "Row1 Col4"],
    ["Row2 Col1", "Row2 Col2", "Row2 Col3", "Row2 Col4"]
]

# 将数据填入表格
for row_idx, row_data in enumerate(data):
    row = table.rows[row_idx]
    for col_idx, cell_data in enumerate(row_data):
        cell = row.cells[col_idx]
        cell.text = cell_data

# 保存文档
doc.save(r'C:\Users\Administrator\Desktop\Word文档\example.docx')

备注:操作前需要关闭word软件。

相关推荐
liuyunshengsir7 分钟前
PyTorch 动态量化(Dynamic Quantization)
人工智能·pytorch·python
电子云与长程纠缠16 分钟前
UE5制作六边形包裹球体效果
开发语言·python·ue5
DFT计算杂谈25 分钟前
KPROJ编译教程
java·前端·python·算法·conda
xiaoshuaishuai81 小时前
C# 签名异常与Gas预估失败调试方案
开发语言·网络·tcp/ip·c#
xiaoshuaishuai81 小时前
C# Gemini 辅助网络安全漏洞分析
开发语言·web安全·c#
念恒123061 小时前
Python(循环中断)
开发语言·python
风继续吹..1 小时前
C# 文件输入输出 精简理解
开发语言·c#
tsfy20031 小时前
Python 处理中文文件名的3个坑(附 Flask 上传解决函数)
开发语言·python·flask·文件上传·中文编码
AI技术控1 小时前
KV Cache 缓存机制的原理和应用:从 Transformer 推理到大模型服务优化
人工智能·python·深度学习·缓存·自然语言处理·transformer
魔法阵维护师1 小时前
从零开发游戏需要学习的c#模块,第十章(设计模式入门)
学习·游戏·设计模式·c#