python 删除word 某一章节_聊聊python 办公自动化之 Word(中)

原标题:聊聊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, "

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值