将字节串读取为 xls 文件

Read byte string as xls file

我有一个从 RabbitMQ 队列消费的 JSON 对象,它包含一个 base64 编码的 xls 文件。 结构如下:

{
    "error": false,
    "excel_file": "0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQ...........",
    "other_field": "more data here",
    ...
    ...
}

目前我在做类似的事情:

data = json.loads(msg)  # msg is the body of the message consumed from rabbitmq queue
file_bytes = bytes(data['excel_file'], 'utf8')  # returns: b'0M8R4KGxGuEAAAAAAAAAAAAAAAAAA...
decoded_bytes = base64.b64decode(file_bytes)  # returns: b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00...

# save data to file
with open('file.xls', 'wb') as f:
    f.write(decoded_bytes)

# open the saved file as xls for manipulation
with xlrd.open_workbook('file.xls') as f:
    sh0 = f.sheet_by_index(0)
    print(sh0.name)

"""Manipulate the xls file data with ease.""""

我不想在我的文件系统中创建一个 xls 文件并在操作后删除它。

理想情况下,我想使用 xlrd.loads()(不存在)之类的东西直接将解码数据加载为 xlrd 对象。

就像json.loads()一样。

有谁知道如何从 bytearray 直接加载 xls 数据 进行操作?

更新

正如@Raphael 和@Masklinn 所建议的那样,我利用 xlrd 的 file_contents 直接从字节加载 xls 数据,无需任何文件。

所以现在的代码如下:

data = json.loads(msg)  # msg is the body of the message consumed from rabbitmq queue
decoded_bytes = base64.b64decode(data['excel_file'])  # returns: b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00...

with xlrd.open_workbook(file_contents=decoded_bytes) as f:
    sh0 = f.sheet_by_index(0)
    # manipulate the data as xlrd Book object
    # ....

xlrd 还有一个 file_contents 参数。参见 docs or this other

通常,当您有字节并且需要文件句柄时,您也可以使用 BytesIOio.BytesIO(bytes) 的行为与 open('file.bytes', 'rb)

完全相同