django如何通过HttpResponse返回一个文件(如:表格)?
方案
视图
from rest_framework import APIView
import pandas as pd
import BytesIO
class View(APIView):
def get(self, request):
df = pd.read_excel('表格.xlsx')
with BytesIO() as io:
df.to_excel(io)
res = HttpResponse(io.getvalue(), content_type='application/octet-stream; charset=utf8')
# filename如果有中文必需编码下,要不会造成下载失败
filename = '表格.xlsx'.encode('utf8').decode('ISO-8859-1') # 为了保证中文名正常显示
res['Content-Disposition'] = f'attachement; filename={filename}'
return res
视图写法请结合自己的实际情况,只需要参考具体实现即可