Python 写入Word
首先要下载库 Python -docx.
可以直接pip下载,pip install python-docx
# coding:utf-8
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading(u'Python 操作Word实例', 3) #直接添加标题
#先定义标题,再添加内容
p_total = document.add_heading()
r_total = p_total.add_run("执行结果如下:")
r_total.font.bold = True
# 增加表格
table = document.add_table(rows=1, cols=3, style="Light List Accent 5")
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'testName'
hdr_cells[1].text = 'param'
hdr_cells[2].text = 'exc'
for i in range(5):
i = i + 1
testName = "testName"+str(i)
img_name = "D:/test.jpg"
param = "param"+str(i)
exc="exc"+str(i)
row_cells = table.add_row().cells
row_cells[0].text = testName
row_cells[1].text = param
row_cells[2].text = exc
#添加二级标题
p_total = document.add_heading("", 2)
r_total = p_total.add_run(testName)
r_total.font.bold = True
document.add_picture(img_name, width=Inches(1.5)) # 向文档里添加图片
document.save("D:/test.docx") # 保存文档
执行结果如下: