本文所指的 word文档,都是docx结尾的,如果是doc结尾的,请参考上篇:点我
我们绝大多数的需求都是 利用python-docx 来读取word文档中的内容,进而再对内容进行其他处理,如下代码,就是读取所有的段落:
from docx import DocumentdocStr = Document("您的docx文件的路径")for paragraph in docStr.paragraphs:parStr = paragraph.textprint(parStr)
但是这样会有一个问题,就是如果在某处插入一个 文本框,那么就读不出来,原因很简单,就是属性不同
1、读取word中插入的文本框里的内容:
from docx import DocumentdocStr = Document("您的docx文件的路径")children = docStr.element.body.iter()count = 0 #写一个count是为了,可以定位是哪个文本框,因为我用索引失败了for child in children:# 通过类型判断目录if child.tag.endswith('txbx'):for ci in child.iter():if ci.tag.endswith('main}r'):count += 1# if count == 1:print(ci.text)docStr.save("您的保存路径")
2、修改(就不贴图啦)
因为我这里用索引失败了,所以我用了一个变量 count,您可以用count==几,依次来定位是第几个文本框,这样您就可以修改里面的内容
from docx import DocumentdocStr = Document("您的docx文件的路径")children = docStr.element.body.iter()count = 0 #写一个count是为了,可以定位是哪个文本框,因为我用索引失败了for child in children:# 通过类型判断目录if child.tag.endswith('txbx'):for ci in child.iter():if ci.tag.endswith('main}r'):count += 1# if count == 1:print(ci.text)ci.tesx = "可直接赋值"docStr.save("您的保存路径")