简体   繁体   English

如何使用fastapi在浏览器中下载由xlsxwriter生成的excel文件?

[英]How to download excel file that is generated by xlsxwriter in browser with using fastapi?

I am using xlsxwriter for python to generate excel files.我正在使用 xlsxwriter for python 来生成 excel 文件。 The file is generated in my root folder.该文件在我的根文件夹中生成。 I want to download the file with the browser when the url is hit.我想在点击 url 时用浏览器下载文件。 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.最好使用网络服务器(nginx、apache 等)来提供文件。

Also, you can implement it in a FastAPI endpoint like the below:此外,您可以在 FastAPI 端点中实现它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM