Python Word基本操作

1. 安装 python-docx

bash

pip install python-docx

2. 基本文档操作

新建Word文档

Python

from docx import Document

doc = Document()
doc.save('my_word.docx')

打开现有文档

Python

from docx import Document

doc = Document('my_word.docx')

3. 添加和操作段落/文本

添加段落

Python

doc = Document()
doc.add_paragraph('Hello, World!')
doc.save('demo.docx')

向段落添加文本(续写)

Python

para = doc.add_paragraph('第一部分。')
para.add_run('这是附加的文字。')
doc.save('add_text.docx')

读取所有段落

Python

for para in doc.paragraphs:
    print(para.text)

改变字体、加粗、斜体

Python

para = doc.add_paragraph('加粗和斜体:')
run = para.add_run('Bold and Italic')
run.bold = True
run.italic = True
doc.save('style.docx')

4. 操作标题

Python

doc.add_heading('一级标题', level=1)
doc.add_heading('二级标题', level=2)
doc.save('heading.docx')

5. 插入/读取表格

插入表格

Python

# 2行3列的表格
table = doc.add_table(rows=2, cols=3)
table.style = 'Table Grid'
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '年龄'
table.cell(0, 2).text = '性别'
table.cell(1, 0).text = '张三'
table.cell(1, 1).text = '20'
table.cell(1, 2).text = '男'
doc.save('table.docx')

读取表格内容

Python

for table in doc.tables:
    for row in table.rows:
        print([cell.text for cell in row.cells])

6. 插入图片

Python

doc.add_picture('test.jpg', width=Inches(2))  # 需要 from docx.shared import Inches
doc.save('picture.docx')

7. 分页符

Python

from docx.enum.text import WD_BREAK

para = doc.add_paragraph()
run = para.add_run()
run.add_break(WD_BREAK.PAGE)
doc.save('break.docx')

8. 设置段落格式

Python

from docx.shared import Pt

para = doc.add_paragraph('段落缩进和行距')
para.paragraph_format.first_line_indent = Pt(24)   # 首行缩进
para.paragraph_format.line_spacing = 1.5           # 行距
doc.save('para_format.docx')

9. 设置字体(中文支持)

Python

from docx.oxml.ns import qn
from docx.shared import Pt

para = doc.add_paragraph()
run = para.add_run('中文字体显示')
run.font.name = '微软雅黑'
run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')
run.font.size = Pt(16)
doc.save('font_cn.docx')

10. 读取与查找/替换文字

查找(模糊)

Python

for para in doc.paragraphs:
    if '目标文字' in para.text:
        print(para.text)

替换(简单)

Python

for para in doc.paragraphs:
    if '旧词' in para.text:
        para.text = para.text.replace('旧词', '新词')
doc.save('replaced.docx')

11. 更多技巧和注意事项

  • 批量处理 Word 文档:遍历文件夹批量打开、编辑、保存。
  • 合并多个文档:通过读取一个文档内容插入另一个文档。
  • 读写页眉页脚doc.sections[0].header, .footer
  • 只支持 docx,不支持老 .doc 格式。

参考项目/常见场景

  • 简历、合同、报告自动生成
  • Excel 与 Word 联动(如与 openpyxl 配合)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值