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

相关推荐
Csvn15 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891816 小时前
Python主流框架全解析
开发语言·python
sg_knight16 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财16 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40817 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339917 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz17 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据17 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby17 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧18 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python