8 python-docx

8.1 项目简介

python-docx是用于创建和更新Microsoft Word(.docx)文件的Python库。

8.2 项目地址

https://github.com/python-openxml/python-docx

8.3 文档地址

https://python-docx.readthedocs.io/en/latest/

8.4 最佳实践

pip3 install python-docx
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(' and some ')
p.add_run('italic.').italic = True

document.add_heading('1级标题', level=1)
document.add_paragraph('强烈的引述', style='Intense Quote')

document.add_paragraph(
    '无序列表中的第一项', style='List Bullet'
)
document.add_paragraph(
    '有序列表中的第一项', style='List Number'
)

# 添加图片
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 = '单元格1'
hdr_cells[1].text = '单元格2'
hdr_cells[2].text = '单元格3'
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

document.add_page_break()

document.save('demo.docx')


© pengpeng 本站总访问量修改时间: 2020-07-26

results matching ""

    No results matching ""