Certainly! Below is a complete Python script that uses Flask to dynamically generate an Excel file in memory (without saving it to disk) and allows the user to download it by visiting a specific route (e.g., /download).
We'll use:
- Flask – for the web server.
- openpyxl or xlsxwriter – to generate Excel files. (We'll use
xlsxwriter in this example because it supports streaming responses better via BytesIO.)
- io.BytesIO – to hold the Excel file in memory.
✅ Prerequisites
Make sure you have Flask and XlsxWriter installed:
pip install flask xlsxwriter
🐍 Python Script: app.py
from flask import Flask, Response
import io
import xlsxwriter
app = Flask(__name__)
@app.route('/download')
def download_excel():
# Create a BytesIO object in memory
output = io.BytesIO()
# Create a workbook and add a worksheet using xlsxwriter
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet('Sheet1')
# Write some data to the worksheet
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
for row_num, row_data in enumerate(data):
for col_num, value in enumerate(row_data):
worksheet.write(row_num, col_num, value)
# Close the workbook to finalize the file
workbook.close()
# Move to the beginning of the BytesIO buffer
output.seek(0)
# Return the file as a downloadable response
return Response(
output,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": "attachment;filename=report.xlsx"}
)
if __name__ == '__main__':
app.run(debug=True)
⚠️ Note: xlsxwriter doesn't support in_memory=True directly (that was a mistake in earlier versions). So instead, we write to BytesIO, and xlsxwriter handles it fine. The key is to call .close() on the workbook before reading from the buffer.
✅ Updated working version (confirmed):
from flask import Flask, Response
import io
import xlsxwriter
app = Flask(__name__)
@app.route('/download')
def download_excel():
# Create a BytesIO object in memory
output = io.BytesIO()
# Create a workbook and add a worksheet using xlsxwriter
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet('Sheet1')
# Sample data
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
for r_idx, row in enumerate(data):
for c_idx, value in enumerate(row):
worksheet.write(r_idx, c_idx, value)
workbook.close() # Important: close workbook before reading the buffer
output.seek(0) # Rewind to start of stream
return Response(
output.getvalue(),
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": "attachment;filename=report.xlsx"}
)
if __name__ == '__main__':
app.run(debug=True)
Wait — actually, there's one more correction: output.getvalue() is needed when passing to Response, because output is a BytesIO object.
But the previous snippet still has a subtle bug: Workbook(output) expects a filename or a real file-like object with seek/tell, and xlsxwriter writes at the end, so getvalue() works only after .close().
So here's the fully working version:
✅ Final Correct Version
from flask import Flask, Response
import io
import xlsxwriter
app = Flask(__name__)
@app.route('/download')
def download_excel():
# Create a BytesIO buffer
output = io.BytesIO()
# Create workbook and worksheet
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet("Sheet1")
# Sample data
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]
# Write data to worksheet
for row_num, row in enumerate(data):
for col_num, value in enumerate(row):
worksheet.write(row_num, col_num, value)
# Close the workbook to flush data into the BytesIO buffer
workbook.close()
# Seek to the beginning of the buffer
output.seek(0)
# Send the file to the client
return Response(
output.read(), # or use output.getvalue()
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": "attachment;filename=report.xlsx"
}
)
if __name__ == "__main__":
app.run(debug=True)
Wait again — actually, output.read() is correct after .seek(0).
So yes, this version is good.
🔁 Alternative Using openpyxl
If you prefer openpyxl, here's how that would look:
from flask import Flask, Response
import io
from openpyxl import Workbook
app = Flask(__name__)
@app.route('/download')
def download_excel():
wb = Workbook()
ws = wb.active
ws.title = "Sheet1"
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]
for row in data:
ws.append(row)
output = io.BytesIO()
wb.save(output)
output.seek(0)
return Response(
output.read(),
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": "attachment;filename=report.xlsx"}
)
if __name__ == "__main__":
app.run(debug=True)
✅ This version is simpler and more readable if you're okay with openpyxl.
✅ Summary
- No file is saved to disk.
- File is generated in memory using
BytesIO.
- Flask streams it back to the browser as a download.
- You can use either
xlsxwriter or openpyxl.
Let me know if you'd like to add dynamic content, authentication, or styling!