Created
June 9, 2022 09:36
-
-
Save stephansemerad/897d3b204fc637c2712bb11d8994dc3b to your computer and use it in GitHub Desktop.
Example of download excel file with Buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import openpyxl | |
from openpyxl import load_workbook | |
from io import BytesIO | |
from flask import Flask, jsonify, Response | |
app = Flask(__name__) | |
@app.route("/") | |
def index(): | |
return jsonify({"message": "Hello World"}) | |
@app.route("/download") | |
def download(): | |
# Would be coming from DB. | |
data = [ | |
{"name": "John", "age": "26", "city": "New York"}, | |
{"name": "Steward", "age": "27", "city": "New York"}, | |
{"name": "Frank", "age": "28", "city": "New York"}, | |
] | |
wb = load_workbook("template.xlsx") | |
ws = wb["overview"] | |
h = 5 | |
for i in data: | |
ws[f"B{h}"].value = i["name"] | |
ws[f"C{h}"].value = i["age"] | |
ws[f"D{h}"].value = i["city"] | |
h += 1 | |
buffer = BytesIO() | |
wb.save(buffer) | |
headers = {"Content-Disposition": "attachment; filename=output.xlsx", "Content-type": "application/vnd.ms-excel"} | |
return Response(buffer.getvalue(), headers=headers) | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=5000, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment