简体   繁体   中英

How to encode an Excel File to base64

I need to use SendGrid to send emails from my application. I've made the transactional templates in sendgrid and now need to attach excel to the emails that go out.

According to their Web API V3 documentation, the attachment can be added by encoding the file in Base64. I've tried searching for solutions to encode the file in Base64, but can't find a solution to it. From what I understand of the base64 package, it can only encode bytes-like objects.

So, do I need to read the excel file into a byte-like object before I can encode it? Is there a package that will do this for me magically?

My application currently generates the excel file by using the pandas to_excel() method.

Thanks in advance :)

[Update 1] I've checked this question if mine could be a duplicate, however, that question returns the file as a String, but to do the Base64 encoding, I need a byte-like object to encode my excel file.

I did try the solution provided in that question but it did not work because the final return was a string.

To encode an Excel file to base64, try this

import base64

data = open(excel_path, 'rb').read()
base64_encoded = base64.b64encode(data).decode('UTF-8')

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