1 概述
python 为脚本自动化操作 Word 提供了可能。最为常用是 python-docx .使用它可以方便地创建或更新 Microfoft Word(.docx) files.
下图是其官网给出的一个使用 python-docx 创建的 word 文档的 Demo:
文档地址:http://python-docx.readthedocs.io/en/latest/index.html
github: https://github.com/python-openxml/python-docx
这是官网给出的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') 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='IntenseQuote') document.add_paragraph( 'first item in unordered list', style='ListBullet' ) document.add_paragraph( 'first item in ordered list', style='ListNumber' ) document.add_picture('monty-truth.png', width=Inches(1.25)) 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 item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item.qty) row_cells[1].text = str(item.id) row_cells[2].text = item.desc document.add_page_break() document.save('demo.docx') |
2 安装 python-docx
可以使用 pip 或 easy_install 来进行安装
1 2 3 4 5 |
pip install python-docx 或 easy_install python-docx |
也可以直接下载安装文件来进行安装:
1 2 3 |
tar xvzf python-docx-{version}.tar.gz cd python-docx-{version} python setup.py install |
要求Python 版本在2.6 以上或 3.3 以上,lxml 版本在 2.3.2及以上。 在 Windows 10 / Python 2.7 环境下安装时出现 lxml3.7.2 安装失败的问题,可降低版本进行尝试:
1 |
pip install lxml==3.4.2 |
3 快速上手
3.1 打开文档
1 2 |
from docx import Document document = Document() |
新建一个空的 word 文档。当然,也可以打开一个已存在的 word 文档,只要传入相应的路径就好。