I am using xlsxwriter for python to generate excel files. The file is generated in my root folder. I want to download the file with the browser when the url is hit. I am using the following code.
import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 20)
bold = workbook.add_format({'bold': True})
worksheet.write('A1', 'Hello')
worksheet.write('A2', 'World', bold)
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
workbook.close()
It's better to use a webserver(nginx, apache, etc.) to serve your files.
Also, you can implement it in a FastAPI endpoint like the below:
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/your-path")
def your_api():
# create your excel file here and store the path in file_path
# like this: file_path = "demo.xlsx"
return FileResponse(path=file_path, filename=file_path, media_type='application/vnd.ms-excel')