Tutorial "saving as a stream" (replacement of save_virtual_workbook) code does not work
new recommendation from the developers is to use a temp-file: https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream
However that presents with a runtime Exception
, because wb.save
attempts to open the already-opened (by with
) file.
I ended up having to use this:
from tempfile import NamedTemporaryFile
from openpyxl import Workbook
wb = Workbook()
with NamedTemporaryFile() as tmp:
tmp.close() # with statement opened tmp, close it so wb.save can open it
wb.save(tmp.name)
with open(tmp.name, 'rb') as f:
f.seek(0) # probably not needed anymore
new_file_object = f.read()