繁体   English   中英

将字节字符串读取为 xls 文件

[英]Read byte string as xls file

我有一个 JSON object 来自一个 RabbitMQ 队列,其中包含一个Z95A1446A7120E4AF5C0C2 编码的 xEls78 文件。 结构如下:

{
    "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 object。

就像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参数。 请参阅文档或其他问题

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM