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

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

  • 介绍
  • 效果
  • 代码

介绍

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

效果

插入表格前的word文档:
在这里插入图片描述
插入表格后的word文档:
在这里插入图片描述

代码

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软件。

相关推荐

  1. python创建word文档

    2024-06-11 13:20:03       45 阅读
  2. 如何Python创建使用自定义模块

    2024-06-11 13:20:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-11 13:20:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-11 13:20:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-11 13:20:03       82 阅读
  4. Python语言-面向对象

    2024-06-11 13:20:03       91 阅读

热门阅读

  1. 在Vue中使用websocket的流程

    2024-06-11 13:20:03       28 阅读
  2. 前端实现流文件下载

    2024-06-11 13:20:03       30 阅读
  3. 廉价耐储存食物推荐: 末日生存爱好者

    2024-06-11 13:20:03       33 阅读
  4. C++day5

    C++day5

    2024-06-11 13:20:03      28 阅读
  5. 15年老程序员的内心独白

    2024-06-11 13:20:03       25 阅读
  6. 前端学习笔记(一)

    2024-06-11 13:20:03       26 阅读
  7. c语言基础篇C

    2024-06-11 13:20:03       32 阅读