Python读取docx文档的内容

Python读取docx文档的内容

下载好解析docx文档的包,Python-docx是专门针对于word文档的一个模块。

doc.paragraphs 段落集合
doc.tables 表格集合
doc.sections 节 集合
doc.styles 样式集合
doc.inline_shapes 内置图形 等等

1、读取文档内容

from docx import Document
doc=Document("C:\\Users\\Administrator\\Desktop\\wuyou.docx")  #实例化一个文档对象
for value in doc.paragraphs:  #遍历文档的每一段
    print(value.text)  #输出每一段的内容

2、插入段落

doc.add_paragraph("i name is wuyou")  #插入段落
doc.save("C:\\Users\\吴悠\\Desktop\\wuyou.docx")  #一定要保存,否则之前的操作无效

3、添加标题

doc.add_heading('Document Title',0)  # 这里是给文档添加一个标题,0表示 样式为title,1则为忽略,其他则是Heading{level}
doc.add_heading('Heading, level 1', level=1)  # 这里是添加标题1

4、添加图片

from docx.shared import Inches
doc.add_picture('monty-truth.png', width=Inches(1.25))  # 添加图片

5、添加列表

table = doc.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'

猜你喜欢

转载自blog.csdn.net/qq_39905917/article/details/83503486