简体   繁体   中英

How do I convert an Excel or similar (not just a plain text file) to bytes or binary then back again

I have written an encryption program that I want to be able to encrypt Excel files with and then decrypt them and output a final Excel file. I have decided to read the whole file then encrypt it as it would be easier than reading each cell from the Excel file.

So far I have been able to read the file and convert it to bytes but cannot figure out how to turn it back into an Excel file.

root = Tk()
root.withdraw()

file = filedialog.askopenfile(initialdir="C:")##Creates a file dialog to pick a file
tempFile=open(file.name,encoding="Latin-1")##Encodes it with Latin-1 so all 256 bytes can be read
file.close()

data=tempFile.read()
tempFile.close()

newFile=open("testfile","w",encoding="cp1252")##Creates a new file with cp1252 encoding as that is what Excel uses

newFile.write(data)
newFile.close() ##Currently it just fills the Excel file with a whole bunch of random characters

Edit:

To be more concise, what I want to do is take the data from an Excel file with anything in it, encrypt it, decrypt it and then write it back into a new Excel file with all formatting etc intact. Is there a way to do the reading and writing of the whole file?

I have found the answer to my problem, @furas your comment is what I needed to do:

selectedFile = filedialog.askopenfile(initialdir="C:")
tempFile=open(selectedFile.name,mode="rb")
data=tempFile.read()

newFile=open("test.xlsx",mode="wb")
newFile.write(data)

This creates the exact same file as the original one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM