python-docx - 读写更新 .docx 文件(Microsoft Word 2007+ )

文章目录


一、关于 python-docx

python-docx 是一个Python库,用来 读写更新 Microsoft Word 2007+ (.docx) 文件。


关于 OpenXML

OpenXML,是微软Office 2007及以上版本文档的存储格式,它将文档内容以XML形式存储,使得文档内容可以被程序直接读取和修改。

处理OpenXML所需的库主要是python-docx。



注:不支持 doc 文档

doc 和 docx 有本质诧异,doc 是 二进制,docx 是 XML 格式文件


安装

shell 复制代码
pip install python-docx

二、使用示例

python 复制代码
>>> from docx import Document

>>> document = Document()
>>> document.add_paragraph("It was a dark and stormy night.")
<docx.text.paragraph.Paragraph object at 0x10f19e760>
>>> document.save("dark-and-stormy.docx")

>>> document = Document("dark-and-stormy.docx")
>>> document.paragraphs[0].text
'It was a dark and stormy night.'

python 复制代码
from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

document.add_page_break()

document.save('demo.docx')

2025-03-03

相关推荐
凡尘——雨落凡尘1 小时前
Python列表索引越界IndexError问题深度解析与解决办法
python·indexerror·list index out of range
郝同学今天有进步吗1 小时前
构建 LangGraph Code Review Agent(七):实现规则匹配、Finding Guardrails 与 Markdown 报告
python·ai·fastapi·code review
xuhe22 小时前
一劳永逸!解决 AutoDL 系统盘(30GB)爆满与 pip 缓存迁移
linux·python·ai·jupyter
CodexDave2 小时前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理
m沐沐3 小时前
【深度学习】循环神经网络RNN——结构、原理与长期依赖问题解析
人工智能·pytorch·python·rnn·深度学习·算法·机器学习
风吹心凉3 小时前
python3基础2026.7.28
开发语言·python
曲无忆3 小时前
LLMs赋能依赖类型证明自动化
python
一次旅行3 小时前
act本地预跑GitHub Actions:Python项目完整CI/CD流水线实战
python·ci/cd·github
玉鸯4 小时前
RAG 全链路调优指南:从 Chunking 到 Reranker
python·llm·agent
淼澄研学4 小时前
Python开发AI应用实战:从环境配置到RAG部署的5个核心技术栈
开发语言·人工智能·python