java - 如何使用python解码编码的excel文件
问题描述
我的 java 程序员将一个 excel 文件转换为二进制文件并将二进制内容发送给我。
他使用sun.misc.BASE64Encoder
andsun.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)
推荐阅读
- tsql - 而不是选择一个表,然后从该表中选择:什么是更好的加入方式?
- javascript - 本地 fr angular 5 缺少本地日期
- php - 如果已设置类变量,PHP 强制类具有特定方法
- python - 如果数据框中的列为空,如何创建条件子句?
- c# - 将数据流从 UWP 发送到 WCF
- ios - FBSDKCoreKit 缺乏对 BitCode 的支持
- outlook - 在 Windows 10 上使用 VB6 错误通过 Outlook 发送电子邮件:运行时 287 - 应用程序定义或对象定义错误
- acumatica - PXSelector 与 PXDBScalar 有什么区别
- swift - 从 Firestore 文档中获取单个元素
- python - 如何使用 NLTK 或 stanfordcorenlp 等 python 包在句子中提取场景/放置词?