原标题:聊聊python 办公自动化之 Word(中)
作者:星安果
来源:AirPython(公众号)
上一篇文章,对 Word 写入数据的一些常见操作进行了总结,详情请看聊聊python 办公自动化之 Word(上)。相比写入数据,读取数据同样很实用!本篇文章,将谈谈如何全面读取一个 Word 文档中的数据,并会指出一些要注意的点。
基本信息
我们同样使用 python-docx 这个依赖库来对 Word 文档进行读取。首先我们来读取文档的基本信息,它们分别是:章节、页边距、页眉页脚边距、页面宽高、页面方向等。
在获取文档基础信息之前,我们通过文档路径构建一个文档对象 Document。
from docx import Document
# 源文件目录
self.word_path = './output.docx'
# 打开文档,构建一个文档对象
self.doc = Document(self.word_path)
1 - 章节( Section )
# 1、获取章节信息
# 注意:章节可以设置本页的大小、页眉、页脚
msg_sections = self.doc.sections
print("章节列表:", msg_sections)
# 章节数目
print('章节数目:', len(msg_sections))
2 - 页边距( Page Margin )
通过章节对象的 left_margin、top_margin、right_margin、bottom_margin 属性值可以获取当前章节的左边距、上边距、右边距、下边距
def get_page_margin(section):
"""
获取某个页面的页边距(EMU)
:param section:
:return:
"""
# 分别对应:左边距、上边距、右边距、下边距
left, top, right, bottom = section.left_margin, section.top_margin, section.right_margin, section.bottom_margin
return left, top, right, bottom
# 2、页边距信息
first_section = msg_sections[0]
left, top, right, bottom = get_page_margin(first_section)
print('左边距:', left, ",上边距:", top, ",右边距:", right, ",下边距:", bottom)
返回值的单位是 EMU,和厘米、英尺的转换关系如下:
3 - 页眉页脚边距
页眉边距:header_distance
页脚边距:footer_distance
def get_header_footer_distance(section):
"""
获取页眉、页脚边距
:param section:
:return:
"""
# 分别对应页眉边距、页脚边距
header_distance, footer_distance = section.header_distance, section.footer_distance
return header_distance, footer_distance
# 3、页眉页脚边距
header_distance, footer_distance = get_header_footer_distance(first_section)
print('页眉边距:', header_distance, "