如何使用python解码编码的excel文件

2024-09-30 10:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

他使用sun.misc.BASE64Encoder和{}进行编码。在

我需要使用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

请帮我把这个二进制数据转换成熊猫数据帧。在


Tags: 文件数据内容data二进制javaexcel程序员
2条回答

你快到了。既然解密对象是字节字符串,为什么不使用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编码的对象,熊猫把它转换成excel,那么:

^{pr2}$

要将编码对象写入文件(只需关闭循环: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(decoded_data)
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 ""

相关问题 更多 >

    热门问题