问题描述
众所周知python有很多第三方库,这也是python简单实用的原因。要想用python处理word文档就需要安装python-docx库。
解决方案
1安装python-docx库
首先找到python根目录(就是有python.exe的文件夹)打开Scripts文件夹
Shift+鼠标右键选择在此处打开powershell窗口或者cmd窗口输入pip install python-docx按下回车等待安装完成。
2基本操作语法
2.1打开文档
不填默认为新建一个文档
2.2加入不同等级的标题
2.3添加文本
2.4设置字号
2.5设置英文字体
2.6设置中文字体
2.7设置斜体
2.8 设置粗体
2.9增加引用
2.10 增加列表
Style='List Bullet'为无序
Style='List Number'为有序
2.11添加图片
1.png为图片名称(必须与代码文件在同一个文件夹内)
2.12增加表格
2.13 再增加3行表格元素
2.3增加分页
2.3保存文件
3结合代码
from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.oxml.ns import qn
document = Document()
document.add_heading(u'MS WORD写入测试',0)
document.add_heading(u'一级标题',1)
document.add_heading(u'二级标题',2)
paragraph = document.add_paragraph(u'我们在做文本测试!')
run = paragraph.add_run(u'设置字号、')
run.font.size = Pt(24)
run = paragraph.add_run('Set Font,')
run.font.name = 'Consolas'
run = paragraph.add_run(u'设置中文字体、')
run.font.name=u'宋体'
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
run = paragraph.add_run(u'斜体、')
run.italic = True
run = paragraph.add_run(u'粗体').bold = True
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph(
u'无序列表元素1', style='List Bullet'
)
document.add_paragraph(
u'无序列表元素2', style='List Bullet'
)
document.add_paragraph(
u'有序列表元素1', style='List Number'
)
document.add_paragraph(
u'有序列表元素2', style='List Number'
)
document.add_picture('1.png', width=Inches(1.25))
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for i in range(3):
row_cells = table.add_row().cells
row_cells[0].text = 'test'+str(i)
row_cells[1].text = str(i)
row_cells[2].text = 'desc'+str(i)
document.add_page_break()
document.save(u'测试.docx')
4生成效果