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 !=1ornot 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()
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():ifnot name.startswith("word/embeddings/"):continuewith zip_file.open(name)as f:ifnot 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,"当前ole对象不是Excel文件:", e)