首页 > 解决方案 > 如何使用python解码编码的excel文件

问题描述

我的 java 程序员将一个 excel 文件转换为二进制文件并将二进制内容发送给我。

他使用sun.misc.BASE64Encoderandsun.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

请帮我将此二进制数据转换为熊猫数据框。

标签: javapythonpandasencodingbase64

解决方案


您快到了。既然解密的对象是一个字节串,为什么不使用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)

推荐阅读