Python讀取Word文檔中的Excel嵌入文件的方法詳解
今天群友提出一個問題:
給出Word示例如下:
對于這種嵌入文件在Word中都屬于ole文件。
下面我們假設(shè)需要讀取每個嵌入的Excel文件中的python工作表中的A1單元格。
python調(diào)用宏實現(xiàn)
首先我們看看如何調(diào)用com接口的宏代碼實現(xiàn)這個效果,最終完整代碼如下:
from win32com import client as win32 import os word = win32.Dispatch("Word.Application") word.Visible = True wdDoc = word.Documents.Open(os.path.abspath("test.docx")) try: for shape in wdDoc.InlineShapes: if shape.Type != 1 or not shape.OLEFormat.ProgID.startswith("Excel.Sheet"): # 要求形狀類型為wdInlineShapeEmbeddedOLEObject,是Excel類型的OLE對象 continue shape.OLEFormat.Open() xlApp = win32.GetActiveObject('Excel.Application') book = xlApp.Workbooks(1) print([sht.Name for sht in book.Sheets]) print(book.Sheets("python").Range("A1").Value) book.Close() finally: wdDoc.Close() xlApp.Quit() word.Quit()
執(zhí)行結(jié)果:
['java', 'forever', 'python']
python
['java', 'forever', 'python']
python hello world
['java', 'forever', 'python']
python
注意:此方法僅支持在已安裝辦公軟件(office或WPS)的windows環(huán)境下使用。
python解析ole文件實現(xiàn)
我通過壓縮軟件看到三個Excel文件其實是以ole的bin文件形式存儲:
我們也只需要理解并解析這些文件就可以得到對應(yīng)的Excel文件,然后直接使用openpyxl或pandas解析。
HY.Li大佬提供了對應(yīng)的代碼:
思路與我的想法不謀而合,不過我不知道用olefile這個現(xiàn)成的庫可以解析這些文件,原本還打算自己實現(xiàn)一下。
參考上面的代碼,最終我的實現(xiàn)如下:
import olefile from zipfile import ZipFile from openpyxl import load_workbook filename = "test.docx" with ZipFile(filename, "r") as zip_file: for name in zip_file.namelist(): if not name.startswith("word/embeddings/"): continue with zip_file.open(name) as f: if not olefile.isOleFile(f): continue ole = olefile.OleFileIO(f) try: book = load_workbook(ole.openstream("package")) print(book.sheetnames) print(book["python"]["A1"].value) except Exception as e: print(name, "當(dāng)前ole對象不是Excel文件:", e)
結(jié)果:
['java', 'forever', 'python']
python
['java', 'forever', 'python']
python hello world
['java', 'forever', 'python']
python
相對來說,此方法跨平臺,速度快。
到此這篇關(guān)于Python讀取Word文檔中的Excel嵌入文件的方法詳解的文章就介紹到這了,更多相關(guān)Python讀取Word中的Excel嵌入文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python創(chuàng)建二維數(shù)組與初始化的實踐舉例
二維數(shù)組使用簡便可以有很多簡潔的操作,實現(xiàn)多元的要求,下面這篇文章主要給大家介紹了關(guān)于Python創(chuàng)建二維數(shù)組與初始化的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12Python3實現(xiàn)發(fā)送QQ郵件功能(html)
這篇文章主要為大家詳細(xì)介紹了Python3實現(xiàn)發(fā)送QQ郵件功能,html格式的qq郵件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12wxpython中自定義事件的實現(xiàn)與使用方法分析
這篇文章主要介紹了wxpython中自定義事件的實現(xiàn)與使用方法,結(jié)合實例形式詳細(xì)分析了wxpython中自定義事件的創(chuàng)建步驟與使用方法,需要的朋友可以參考下2016-07-07pytorch中retain_graph==True的作用說明
這篇文章主要介紹了pytorch中retain_graph==True的作用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02TensorFlow MNIST手寫數(shù)據(jù)集的實現(xiàn)方法
MNIST數(shù)據(jù)集中包含了各種各樣的手寫數(shù)字圖片,這篇文章主要介紹了TensorFlow MNIST手寫數(shù)據(jù)集的實現(xiàn)方法,需要的朋友可以參考下2020-02-02