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

2022-12-16 635阅读

温馨提示:这篇文章已超过496天没有更新,请注意相关的内容是否还可用!

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

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

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

红色圈住的部分就是今天的主角,三个 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里的附件有效。