[Python] Office Automation Chapter Three-Python Operation Word Document

I recorded the excel sheet and drawing of the python automated office operation. Although the recorded operation functions are relatively simple, I will continue to improve the records of these blogs in the process of continuous learning. Come on! There are certainly many tools commonly used in automated office, and today’s record is Python operating word documents.

 

First you need to install the python-docx library, and then use the import docx, such as the following code:

from docx import Document

#新建word文档
document = Document()
document.save('new.docx')

#修改文档
document1 = Document('new.docx')
document1.save('new1.docx')

Python functions commonly used to manipulate word documents:

The functions of these methods are very intuitive. I believe that you can basically understand what these methods do by seeing the names of these methods, so I won't repeat them here. Let's take a look at an example after using them in actual combat:

 

from docx import Document

#定义插入图像的英寸
from docx.shared import Inches

document = Document()
#新增段落
p2 = document.add_paragraph('这是一个段落')

#插入一个段落
p1 = p2.insert_paragraph_before('这是第一个段落')

#新增标题,level 有0-9,level=0会带有下划线样式
document.add_heading('这是标题哦', level=1)

#新增分页符, 后面的内容会添加到新一页中
document.add_page_break()

#新增表格,
table = document.add_table(rows=6, cols=6)

#第一行第三列,从0开始
cell = table.cell(0, 2)
cell.text = '这是第一行第三列'

row = table.rows[1]
row.cells[0].text = '这是第二行第一列'
row.cells[1].text = '这是第二行第二列'

#添加图片
document.add_picture('../data/image/1.jpg', width=Inches(1.25))
document.save('new.docx')


 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/107860311