工具包使用python-docx
Github页面:https://github.com/python-openxml/python-docx
官网教程:https://python-docx.readthedocs.io/en/latest/index.html
中文的非官方教程推荐:http://www.imooc.com/wiki/officeautomation/writeword.html
示例代码
from docx import Document
document = Document() # 新建文档对象
document.add_heading('Document Title', level=0) # 添加标题
# 段落样式设置
p = document.add_paragraph('A plain paragraph having some ') # 添加段落内容,不设置样式则默认为word的默认样式
# 在段落中追加信息
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') # 添加段落
f1 = document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)
f1.insert_paragraph_before("后面添加但是需要前置的信息")
# 添加图片
# from docx.shared import Inches
# 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
# 页眉页脚
header = document.sections[0].header # 获取第一个节的页眉
header.add_paragraph('第一节的页眉')
footer = document.sections[0].footer # 获取第一个节的页脚
footer.add_paragraph('第一节的页脚') # 为第一页添加页脚
# 添加空白页
document.add_page_break()
document.save('demo.docx') # 保存后导出