创建 Word、写入标题、正文、列表、表格、保存文件、读取 Word
一、先安装依赖
pip3 install python-docx
二、创建一个 Word 文档(全自动)
创建文件:test_word.py
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
# 1. 创建文档
doc = Document()
# 2. 添加标题
title = doc.add_heading('我的第一个 Word 文档', 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中
# 3. 添加段落
p1 = doc.add_paragraph('这是使用 Python 自动生成的正文内容。')
# 4. 添加带样式的文字
p2 = doc.add_paragraph('')
p2.add_run('加粗文字').bold = True
p2.add_run(',')
p2.add_run('斜体文字').italic = True
# 5. 添加列表
doc.add_paragraph('项目 1:学习 Python', style='List Bullet')
doc.add_paragraph('项目 2:操作 Word', style='List Bullet')
doc.add_paragraph('项目 3:自动办公', style='List Bullet')
# 6. 添加表格
table = doc.add_table(rows=3, cols=2)
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '年龄'
table.cell(1, 0).text = '张三'
table.cell(1, 1).text = '20'
table.cell(2, 0).text = '李四'
table.cell(2, 1).text = '22'
# 7. 保存文档
doc.save('/home/simpleweb/my_word.docx')
print("Word 创建成功!路径:/home/simpleweb/my_word.docx")
三、读取word
from docx import Document
# 打开文档
doc = Document('/home/simpleweb/my_word.docx')
# 读取所有段落
print("=== 读取 Word 内容 ===")
for para in doc.paragraphs:
print(para.text)四、常用功能
1、插入分页
doc.add_page_break()
2、插入图片
doc.add_picture('test.png', width=Inches(4))
3、设置字体大小 颜色
from docx.shared import Pt
from docx.oxml.ns import qn
run = p1.add_run('我是红色大字')
run.font.size = Pt(16)
run.font.color.rgb = RGBColor(255, 0, 0)
4、追加内容到已有word
doc = Document('my_word.docx')
doc.add_paragraph('这是追加的内容')
doc.save('my_word.docx')