Python utility module (30) python-docx

environment

foreword

python-docx is a library that can create and update word , the Microsoft word processor. Official warehouse address: https://github.com/python-openxml/python-docx .

Install python d-docx , you can use pip directly

 pip install python-docx

use

Let’s take a look at an example of document creation

 from docx import Document from docx.shared import Inches # 实例化一个文档对象document = Document() # 添加标题,用参数level来指定级数document.add_heading('一级标题', level=0) # 添加文字段落p = document.add_paragraph('欢迎大家访问我的网站') document.add_heading('二级标题', level=1) document.add_paragraph('博客地址是: https://xugaoxiang.com', style='Intense Quote') document.add_paragraph( '这是我的学习及实践笔记,希望对您有用!', style='List Bullet' ) document.add_paragraph( '感兴趣的,可以加我知识星球,扫描下方二维码加入', style='List Number' ) # 添加一张图片document.add_picture('zsxq.jpg', width=Inches(2)) datas = ( ('张三', '男', '20'), ('李四', '女', '30'), ('王五', '男', '40') ) # 添加表格table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = '姓名' hdr_cells[1].text = '性别' hdr_cells[2].text = '年龄' for name, sex, age in datas: row_cells = table.add_row().cells row_cells[0].text = str(name) row_cells[1].text = sex row_cells[2].text = age # 跳转到下一页document.add_page_break() # 保存文档document.save('demo.docx')

After executing the code, generate demo.docx

Next, look at an example of document modification

 from docx import Document # 读取上面生成的文档document = Document('demo.docx') pgs = document.paragraphs # 在每个段落的后面添加一个字符串for pg in pgs: pg.text += ',添加的内容' # 获取所有表格,tables是一个列表tables = document.tables # 按行来处理for col in tables[0].columns: for row in col.cells: print(row.text) # 按列来处理for row in tables[0].rows: for col in row.cells: print(col.text) # 修改第一行第二列的标题cell = tables[0].cell(0, 1) cell.text += ':sex' # 另存为document.save('new.docx')

After execution, get a new document

Topics in Python Practical Modules

More useful python modules, please move

https://xugaoxiang.com/category/python/modules/

This article is reprinted from https://xugaoxiang.com/2022/05/10/python-module-30-python-docx/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment