import pathlib
from docx import Document
from docx.shared import Inches, Pt
from docx.oxml.ns import qn
path = list(pathlib.Path.cwd().parents)[1].joinpath(
'data/automate/003word'
)
out_path = path.joinpath(
'003word_create.docx'
)
img_path = path.joinpath(
'dance.jpg'
)
document = Document()
document.add_heading(
'Python1024_自动生成标题'
, 0)
document.add_heading(
'基本:文本'
, level=1)
p = document.add_paragraph(
'测试文本\n测试内容\n'
)
p.add_run(
'粗体部分内容\n'
).bold = True
p.add_run(
'斜体部分\n'
).italic = True
p.add_run(
'下划线部分\n'
).underline = True
p.add_run(
'字体设置\n'
).font.size = Pt(24)
# 测试第三方字体
x = p.add_run(
'三方字体测试\n'
)
x.font.name =
'Source Han Sans CN'
# 思源字体
x.element.rPr.rFonts.set(qn(
'w:eastAsia'
),
'Source Han Sans CN'
)
# 段落和引用
document.add_heading(
'标题一:段落'
, level=1)
document.add_paragraph(
'引用块'
, style=
'Intense Quote'
)
document.add_heading(
'标题1.1、无序列表'
, level=2)
opts = [
'选项1'
,
'选项2'
,
'选项3'
]
# 无需列表
for
opt
in
opts:
document.add_paragraph(opt, style=
'List Bullet'
)
document.add_heading(
'标题1.2、有序列表'
, level=2)
# 有序列表
for
opt
in
opts:
document.add_paragraph(opt, style=
'List Number'
)
document.add_heading(
'标题二:图片'
, level=1)
document.add_picture(str(img_path), width=Inches(5))
document.add_page_break()
document.add_heading(
'标题三:表格'
, level=1)
records = (
(1,
'电风扇'
,
'无叶风扇'
),
(2,
'吹风机'
,
'离子风机'
),
(3,
'Macbook pro'
,
'Apple macbook pro 15寸'
)
)
# 表格
table = document.add_table(rows=1, cols=3)
# 表头
hdr_cells = table.rows[0].cells
hdr_cells[0].text =
'数量'
hdr_cells[1].text =
'ID'
hdr_cells[2].text =
'描述信息'
# 表格数据
for
qty, cid, desc
in
records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = cid
row_cells[2].text = desc
# 保存文档
document.save(out_path)