从字节串中读取 .xlsx 文件

Reading .xlsx file from a bytestring

我正在尝试从电子邮件中读取附加的 .xlsx 文件。

我已经能够检索到一个 email.message.Message 类型,它具有 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 类型的一部分。我应该可以使用

阅读它
file = part.get_payload(decode=True)

这给了我一个以

开头的字节对象
b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x00\x93\xe11\xb6\x93\x01\x00\x003\x07\x00\x00\x13\x00\

我想使用

将其解析成字典
io.BytesIO(gzip.decompress(file))

对于某些带有压缩 .csv 文件的电子邮件,此方法有效,但无法使用此方法打开 .xlsx 文件。我在网上看过,但找不到任何解决方案。任何帮助将不胜感激。

.xlsx 是 ZIP 而不是 GZip 存档。这是两种完全不同的格式。

虽然您可以使用 zipfile 模块来获取其内容,但您仍然需要一些专门的 Excel 文件包来理解它们。

Excel 文件以压缩形式出现,加载到 Excel 本身时会自动解压缩。

openpyxl库可以直接加载这些Excel文件,例如:

import openpyxl
import io

xlsx = io.BytesIO(part.get_payload(decode=True))
wb = openpyxl.load_workbook(xlsx)
ws = wb['Sheet1']

for cells in ws.iter_rows():    
    print([cell.value for cell in cells])

在你的情况下,

import openpyxl
import io

# The bytes object (Something like b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00...)
file = part.get_payload(decode=True)

xlsx = io.BytesIO(file)
wb = openpyxl.load_workbook(xlsx)
ws = wb['Sheet1']

for cells in ws.iter_rows():    
    print([cell.value for cell in cells])