lte__
lte__

Reputation: 7586

Pandas XLSWriter - return instead of write

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()

will write the Excel file to the file system. How can I return the file instead of writing it?

Upvotes: 3

Views: 502

Answers (1)

Michael
Michael

Reputation: 1009

You can write the excel data to memory using a StringIO or BytesIO object.

This code is 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()

Upvotes: 3

Related Questions