[英]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
# ....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.