咔片PPT · AI自动生成演示文稿,模板丰富、排版精美 讯飞智文 · 一键生成PPT和Word,高效应对学习与办公

Python-Docx的官网提供了使用文档:该文档说明了如何使用Python-Docx的所有功能,并包含完整的API参考。在下载中包含的示例中也很好地展示了Python-Docx的功能。

文档地址

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

安装

pip install python-docx

这里直接用代码给大家演示,如何生成下图所示的文档:

  1. 导入python-docx库
  2. 新建wrod文档、一级、二级、三级标题、自然段
  3. 设置字体格式
  4. 在指定位置添加图片
  5. 在指定位置添加表格
  6. 文档另存为

docx import Document 3from docx.shared import Inches 4 5document = Document() 6 7document.add_heading('Document Title', 0) 8# 2、新建wrod文档、一级、二级、三级标题、自然段 9p = document.add_paragraph('A plain paragraph having some ') 10# 3、设置字体格式 11p.add_run('bold').bold = True 12p.add_run(' and some ') 13p.add_run('italic.').italic = True 14 15document.add_heading('Heading, level 1', level=1) 16document.add_paragraph('Intense quote', style='Intense Quote') 17 18document.add_paragraph( 19 'first item in unordered list', style='List Bullet' 20) 21document.add_paragraph( 22 'first item in ordered list', style='List Number' 23) 24# 4、在指定位置添加图片 25document.add_picture('monty-truth.png', width=Inches(1.25)) 26 27records = ( 28 (3, '101', 'Spam'), 29 (7, '422', 'Eggs'), 30 (4, '631', 'pam, spam, eggs, and spam') 31) 32# 5、在指定位置添加表格 33table = document.add_table(rows=1, cols=3) 34hdr_cells = table.rows[0].cells 35hdr_cells[0].text = 'Qty' 36hdr_cells[1].text = 'Id' 37hdr_cells[2].text = 'Desc' 38for qty, id, desc in records: 39 row_cells = table.add_row().cells 40 row_cells[0].text = str(qty) 41 row_cells[1].text = id 42 row_cells[2].text = desc 43 44document.add_page_break() 45# 6、文档另存为 46document.save('demo.docx')