0

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()
  • 1
    Which URL? Are you using a web framework already, or are you asking how you can make the generated files available to a browser? – MatsLindh Jun 26 '22 at 15:36
  • 1
    Please change the question title and put `fastapi` in your question title. It helps to others with searching better in google. something like this: `How to download excel file that is generated by xlsxwriter in browser with using fastapi?` – ahmadgh74 Jun 26 '22 at 15:49
  • I am new to Python. Previously I have used phpexcel to generate and download excel by using some header function. I was searching something like that in python. – Tarek Nasif Jun 26 '22 at 15:52

1 Answers1

3

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')
ahmadgh74
  • 801
  • 6
  • 10
  • Now I can download the file but an additional file is stored in my application folder. How to remove the file? – Tarek Nasif Jul 13 '22 at 13:34
  • you cannot remove the file in this api. please choose a path out of the project directory to store your file. you should create a cronjob to remove the files that their creation date is for X hours ago. – ahmadgh74 Jul 18 '22 at 05:27