如何使用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软件。

相关推荐
RSABLOCKCHAIN5 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者6 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
码流怪侠6 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
2401_894915537 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
zhiSiBuYu05179 小时前
Python3 模块开发与应用实战指南
python
颜x小10 小时前
[C#] C++与c#语法对比
开发语言·c++·c#
databook10 小时前
用方差阈值过滤掉“惰性特征”
python·机器学习·scikit-learn
Freak嵌入式10 小时前
MCU 低功耗模式解析:时钟门控、电源门控、深度休眠
人工智能·python·单片机·嵌入式硬件·开源·依赖倒置原则·micropython
weixin_4236521310 小时前
C#使用JObject
开发语言·c#