简体   繁体   English

如何在 fastAPI 中返回 xlsx 文件?

[英]How do I return a xlsx file in fastAPI?

How do I return a xlsx file in fastAPI?如何在 fastAPI 中返回 xlsx 文件?

Using the python module fastAPI , I can't figure out how to return a xlsx file.使用 python 模块fastAPI ,我不知道如何返回 xlsx 文件。
Alse I use openpyxl library to edit my xlsx.此外,我使用 openpyxl 库来编辑我的 xlsx。

@router.get('/omission-download')
async def omissionFileDownload():
    file_like = open('./upload/test2.xlsx', mode="r") 
    return StreamingResponse(file_like, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

And here is my error这是我的错误

  File "/usr/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 12: invalid continuation byte

If anyone knows what to do, I would appreciate it if you could tell me how.如果有人知道该怎么做,如果你能告诉我怎么做,我将不胜感激。

Like Charlie Clark said, you'll want to use FileResponse .就像查理克拉克所说,你会想要使用FileResponse Try this:尝试这个:

@router.get('/omission-download')
async def omissionFileDownload():
    return FileResponse('./upload/test2.xlsx')

However, to directly answer your question, the error stems from the fact that you're trying to parse a file in UTF-8 mode.但是,要直接回答您的问题,错误源于您尝试在 UTF-8 模式下解析文件。 Change the mode to bytes and it'll work.mode更改为字节,它将起作用。

@router.get('/omission-download')
async def omissionFileDownload():
    file_like = open('./upload/test2.xlsx', mode="rb") 
    return StreamingResponse(file_like, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

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

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