利用Python實現讀取Word文檔里的Excel附件
群里有人提出這么一個需求:每天都會傳過來一份 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里的附件有效。
到此這篇關于利用Python實現讀取Word文檔里的Excel附件的文章就介紹到這了,更多相關Python讀取Word中Excel附件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
卸載所有通過pip安裝的Python包的方法總結(Windows系統(tǒng))
這篇文章主要介紹了卸載所有通過pip安裝的Python包的方法總結(Windows系統(tǒng)),文中通過代碼示例和圖文講解的非常詳細,并具有一定的參考價值,需要的朋友可以參考下2024-08-08python量化之搭建Transformer模型用于股票價格預測
這篇文章主要介紹了python量化之搭建Transformer模型用于股票價格預測,文章圍繞主題展開基于python搭建Transformer,需要的小伙伴可以參考一下2022-05-05Mac 安裝 Python3.10 和 配置環(huán)境的詳細教程
這篇文章主要介紹了Mac 安裝 Python3.10 和 配置環(huán)境,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05