利用Python实现读取Word文档里的Excel附件

作者:alitrack 时间:2022-01-21 11:28:18 

群里有人提出这么一个需求:每天都会传过来一份 Word 文档,里面有多个 Excel 附件,需要把 Excel 内容读取出来。

第一反应是使用python-docx[1], 经测试,不支持附件提取。 

然后想 docx 本质就是一个 zip 格式的压缩包,直接当做 zip 包提取吧。

利用Python实现读取Word文档里的Excel附件

红色圈住的部分就是今天的主角,三个 ole 附件。

解压缩

这样问题就变成了从 zip 里提取三个附件,代码如下:

#zipfile为python自带包
from zipfile import ZipFile
with ZipFile("test.docx", "r") as zip:
    for entry in zip.infolist():
        if not entry.filename.startswith("word/embeddings/"):
            continue
        zip.extract(entry.filename)

得到三个 ole 文件。

这段代码等价于下面的 unzip 命令行

unzip  test.docx word/embeddings/*
#返回
Archive:  test.docx
   creating: word/embeddings/
  inflating: word/embeddings/oleObject1.bin
  inflating: word/embeddings/oleObject2.bin
  inflating: word/embeddings/oleObject3.bin

Microsoft OLE2 文件分析与提取

分析

文件提取好后, 使用 file 程序分析,得到

file word/embeddings/oleObject1.bin
#返回
word/embeddings/oleObject1.bin: Composite Document File V2 Document, Cannot read section info

这是一个 Microsoft OLE2 文件,不是我们想要的 Excel,需要进一步分析提取,有请olefile登场。

olefile[2](原名 OleFileIO_PL)是一个 Python 包,用于解析、读写 Microsoft OLE2 文件(也称为 Structured Storage、Compound File Binary Format 或 Compound Document File Format),例如 Microsoft Office 97-2003 文档,MS Office 中的 vbaProject.bin 2007+ 文件、Image Composer 和 FlashPix 文件、Outlook MSG 文件、StickyNotes、多种 Microscopy 文件格式、McAfee 防病毒隔离文件等。

安装

pip install olefile

提取

import olefile
f = "word/embeddings/oleObject1.bin"
if olefile.isOleFile(f):
    with olefile.OleFileIO(f) as ole:
        print(ole.listdir())
    #返回[['\x01Ole'], ['\x03ObjInfo'], ['package']]
    # 经分析只有package里放着我们需要的信息
        bin_data = ole.openstream("package").read()
        fn = f.replace("word/embeddings/","")
        with open(fn, "wb") as output_file:
            output_file.write(bin_data)

再次使用 file 分析

file oleObject1.bin
#返回
oleObject1.bin: Microsoft Excel 2007+

是我们想要的 Excel 文件。

完整代码如下

import olefile
from zipfile import ZipFile
def get_ole(filename):
    with ZipFile(filename, "r") as zip:
        for entry in zip.infolist():
            if not entry.filename.startswith("word/embeddings/"):
                continue
            with zip.open(entry.filename) as f:
                if not olefile.isOleFile(f):
                    continue
                with olefile.OleFileIO(f) as ole:
                    bin_data = ole.openstream("package").read()
                    fn = entry.filename.replace("word/embeddings/","")
           #如果想直接读取,可以把下面两行代码换成需要的代码。
                    with open(fn, "wb") as output_file:
                        output_file.write(bin_data)
if __name__ == '__main__':
    get_ole("/Users/steven/temp/test.docx")

使用正确的后缀保存附件

我想保存的时候使用正确后缀,怎么办?使用filetype[3]获得正确的后缀。

安装

pip install git+https://github.com/h2non/filetype.py

最新版本支持 Office 文档识别

获取后缀

import filetype
ext = filetype.guess_extension("oleObject1.bin")
print(ext)
#返回
xlsx

如果碰到 filetype 无法识别的,就需要考虑 python-magic 或者 file 了。

python-magic[4]是 libmagic 文件类型标识库的 Python 接口。libmagic通过根据预定义的文件类型列表检查文件类型的头文件来识别文件类型。Unix 命令文件file就是依赖该库来实现文件类型判断。

安装

Windows 推荐安装方法

pip install python-magic-bin

Linux 和macOS还需要额外安装libmagic

获取后缀

import magic
m = magic.Magic(extension=True)
ext = m.from_file("oleObject1.bin")
print(ext)
#返回
xlsx

正确的文件名

附件的原始名字是以图片的形式存在,emf 格式, 如果需要获取原始文件名字,需要 OCR 了, 同时还需要找到对应关系,这里就不展开了。

该方法稍作修改,同样对Excel和PPT里的附件有效。

来源:https://mp.weixin.qq.com/s/mLvUYQeLFQYq58tyAgV0tA

标签:Python,Word,Excel,附件
0
投稿

猜你喜欢

  • Python基础语法之变量与数据类型详解

    2022-06-21 17:52:36
  • asp全面解析Server对象

    2008-10-19 17:24:00
  • django+mysql的使用示例

    2022-10-24 20:34:15
  • 解决Python传递中文参数的问题

    2021-04-10 09:00:07
  • Python while、for、生成器、列表推导等语句的执行效率测试

    2021-03-05 02:17:54
  • 极致之美——百行代码实现全新智能语言Lisp

    2010-07-13 13:07:00
  • html风格tooltip效果的实现

    2010-04-08 13:00:00
  • PHP结构型模式之享元模式详解

    2023-05-27 22:38:40
  • JS实现合并json对象的方法

    2023-08-29 15:09:30
  • 详细讲解如何为MySQL数据库添加新函数

    2008-11-27 17:06:00
  • python3爬取各类天气信息

    2022-01-18 06:09:35
  • Python基础之getpass模块详细介绍

    2021-03-06 13:47:13
  • 客齐集社区头像显示效果代码

    2008-04-03 13:15:00
  • Python Django2 model 查询介绍(条件、范围、模糊查询)

    2023-11-02 15:32:09
  • 菜鸟来看看:制作个人主页有诀窍

    2007-10-05 09:03:00
  • ASP中使用Form和QueryString集合

    2007-09-14 10:43:00
  • asp三天学好ADO对象之第二天

    2008-10-09 12:49:00
  • CSS文字排版终极指南

    2010-01-19 10:30:00
  • 利用Python实现数值积分的方法

    2023-07-11 10:16:31
  • 14个出色的jQuery导航菜单实例教程

    2009-12-31 17:23:00
  • asp之家 网络编程 m.aspxhome.com