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

相关推荐
花酒锄作田6 小时前
Postgres - Listen/Notify构建轻量级发布订阅系统
python·postgresql
Thomas.Sir7 小时前
第二章:LlamaIndex 的基本概念
人工智能·python·ai·llama·llamaindex
m0_694845577 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
李昊哲小课8 小时前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
不知名的老吴9 小时前
返回None还是空集合?防御式编程的关键细节
开发语言·python
李昊哲小课9 小时前
Python办公自动化教程 - 第5章 图表创建 - 让数据可视化
python·信息可视化·数据分析·数据可视化·openpyxl
chushiyunen9 小时前
python pygame实现贪食蛇
开发语言·python·pygame
Dream of maid9 小时前
Python-基础2(流程控制)
python
Lenyiin10 小时前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
涛声依旧3931611 小时前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘