openpyxl - TypeError: a bytes-like object is required, not '_io.BytesIO'

Viewed 2990

using openpyxl I wrote and excel file in a bynary object but when I try to save it via the "write" method, I get this exception:

Traceback (most recent call last): File "stack.py", line 13, in file.write(output) TypeError: a bytes-like object is required, not '_io.BytesIO'

how can I solve the issue? below a simple example:

import openpyxl
from io import BytesIO

wb = openpyxl.Workbook()
ws = wb.active
ws.title = "TEST"
output = BytesIO() 

wb.save(output)


file = open("ciao.xlsx", "wb")
file.write(output) # <--- this instruction doesn't work..

file.close()

NOTE: I already know that I can save the excel file directly with openpyxl, but in my real code, I need to save it in a binary file.

1 Answers

You can get a bytes-like object out of the BytesIO output with the getvalue function.

file.write(output.getvalue())

Related