使用python-docx生成Word文档

因为要生成报告书,从身边的朋友来看,PDF对于很多PC用户来说还是不太会用,所以决定用常规的docx格式吧。

安装python-docx

PS C:\JS> pip install python-docx
Collecting python-docx
  Downloading python-docx-0.8.6.tar.gz (5.3MB)
    78% |█████████████████████████▏      | 4.1MB 4.0MB/s eta 0:00:0
    100% |████████████████████████████████| 5.3MB 166kB/s
Requirement already satisfied: lxml>=2.3.2 in c:\users\chang\appdata\local\programs\python\py
thon36\lib\site-packages (from python-docx)
Installing collected packages: python-docx
  Running setup.py install for python-docx ... done
Successfully installed python-docx-0.8.6

用户手册中说,是要依赖lxml >= 2.3.2的

测试

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('文档标题', 0)

p = document.add_paragraph('这是一个自然段 ')
p.add_run('bold').bold = True
p.add_run(' 还有 ')
p.add_run('italic.').italic = True

document.add_heading('1级别标题', level=1)
document.add_paragraph('引用', style='IntenseQuote')

document.add_paragraph(
    '符号列表', style='ListBullet'
)
document.add_paragraph(
    '数字列表t', style='ListNumber'
)

document.add_paragraph('我的微信:')
document.add_picture('me.jpg', width=Inches(3.25))

table = document.add_table(rows=3, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '第一列'
hdr_cells[1].text = '第二列'
hdr_cells[2].text = '第三列'

hdr_cells = table.rows[1].cells
hdr_cells[0].text = '1'
hdr_cells[1].text = '21'
hdr_cells[2].text = 'qwertyuiop'

hdr_cells = table.rows[2].cells
hdr_cells[0].text = '2'
hdr_cells[1].text = '43'
hdr_cells[2].text = 'asdfghjkl'

document.add_page_break()

document.save('demo.docx')

总体来说效果非常完美。

使用python-docx生成Word文档_第1张图片
Paste_Image.png

中文显示,图片显示都正常。样式系统可以使用。表格可以用。分页符也正常。

Word打开时也没有任何的报错。

你可能感兴趣的:(使用python-docx生成Word文档)