# 通过 pip 安装
pip install python-docx
# 导入核心类
from docx import Document
# 新建空白文档
doc = Document()
# 保存到本地
doc.save('example.docx')
doc.add_paragraph('这是一个普通段落。')
doc.add_paragraph('使用自定义样式的段落。', style='Intense Quote')
doc.add_heading('一级标题', level=1)
doc.add_heading('二级标题', level=2)
doc.add_heading('三级标题', level=3)
# 插入图片,宽度设为 5 cm(高度自动等比)
doc.add_picture('logo.png', width=docx.shared.Cm(5))
table = doc.add_table(rows=3, cols=4, style='Light Grid')
# 填充单元格
for i in range(3):
for j in range(4):
table.cell(i, j).text = f'R{i+1}C{j+1}'
# 假设文档里已经有表格
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
para = doc.add_paragraph('使用标题样式')
para.style = 'Heading 2'
para = doc.add_paragraph()
run = para.add_run('加粗斜体')
run.bold = True
run.italic = True
run.underline = True
run.font.size = docx.shared.Pt(14)
section = doc.sections[0]
# 设置页边距(单位为英寸)
section.top_margin = docx.shared.Inches(1)
section.bottom_margin = docx.shared.Inches(1)
section.left_margin = docx.shared.Inches(1)
section.right_margin = docx.shared.Inches(1)
doc.add_page_break()
doc = Document('existing.docx')
# 遍历所有段落
for para in doc.paragraphs:
print(para.text)
from docx import Document
from docx.shared import Cm, Pt, Inches
doc = Document()
# 标题
doc.add_heading('Python‑docx 示例文档', level=1)
# 段落
p = doc.add_paragraph('下面展示了 python-docx 的常用功能。')
p.add_run('(加粗)').bold = True
# 插入图片
doc.add_picture('sample.jpg', width=Cm(8))
# 表格
table = doc.add_table(rows=2, cols=3, style='Medium Grid 1 Accent 1')
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 = '28'
table.cell(1,2).text = '北京'
# 页面设置
section = doc.sections[0]
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
# 保存
doc.save('demo.docx')
demo.docx 将展示标题、段落、图片、表格以及页面布局的效果。