[英]How to decode an encoded excel file using python
我的 java 程序员将一个 excel 文件转换为二进制文件并将二进制内容发送给我。
他使用sun.misc.BASE64Encoder
和sun.misc.BASE64Decoder()
进行编码。
我需要使用 python 将该二进制数据转换为数据框。
数据看起来像,
UEsDBBQABgAIAAAAIQBi7p1oXgEAAJAEAAATAAgCW0NvbnRlbnRfVHl........
我尝试bas64
解码器但没有帮助。
我的代码:
import base64
with open('encoded_data.txt','rb') as d:
data=d.read()
print(data)
`UEsDBBQABgAIAAAAIQBi7p1oXgEAAJAEAAATAAgCW0NvbnRlbnRfVHl........`
decrypted=base64.b64decode(data)
print(decrypt)
'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x00b\xee\x9dh^\x01\x00\x00\x90\x04\x00\x00\x13\x00\x08\x02[Content_Types].xml \xa2\x04\x02(\xa0\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
请帮我将此二进制数据转换为熊猫数据框。
您快到了。 既然解密的对象是字节字符串,为什么不使用BytesIO
呢?
import io
import pandas as pd
toread = io.BytesIO()
toread.write(decrypted) # pass your `decrypted` string as the argument here
toread.seek(0) # reset the pointer
df = pd.read_excel(toread) # now read to dataframe
从您的评论中回答您的问题:如何将 df 转换为二进制编码对象?
好吧,如果您想将其转换回 b64 编码对象,并且 pandas 将其转换为 excel,那么:
towrite = io.BytesIO()
df.to_excel(towrite) # write to BytesIO buffer
towrite.seek(0) # reset pointer
encoded = base64.b64encode(towrite.read()) # encoded object
要将编码对象写入文件(只是为了关闭循环:P):
with open("file.txt", "wb") as f:
f.write(encoded)
您也可以使用 openpyxl 模块这是修改后的代码
import base64
import io
import openpyxl
with open('encoded_data.txt','rb') as d:
data=d.read()
print(data)
decrypted=base64.b64decode(data)
print(decrypted)
xls_filelike = io.BytesIO(decrypted)
workbook = openpyxl.load_workbook(xls_filelike)
sheet_obj = workbook.active
max_col = sheet_obj.max_column
max_row = sheet_obj.max_row
# Will print all the row values
for i in range(1, max_row +1):
for j in range(1, max_col + 1):
cell_obj = sheet_obj.cell(row = i, column = j)
print cell_obj.value,
print ",", "Inorder to seperate the cells using comma for readability
print ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.