Pandas XLSXWriter – returns instead of writing… here is a solution to the problem.
Pandas XLSXWriter – returns instead of writing
I want to return an Excel file from my Flask (Python) server. This code:
writer = pd. ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
Write the Excel file to the file system. How do I return
a file instead of writing to it?
Solution
You can use StringIO
or BytesIO
objects to write excel data to memory.
This code was copied from the pandas documentation here :
# Safe import for either Python 2.x or 3.x
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
bio = BytesIO()
# By setting the 'engine' in the ExcelWriter constructor.
writer = ExcelWriter(bio, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
# Save the workbook
writer.save()
# Seek to the beginning and read to copy the workbook to a variable in memory
bio.seek(0)
workbook = bio.read()