django使用pandas下载excel文件

最开始是将数据库数据写到本地excel中,再读出来返回给前端,后面发现可以使用BytesIO(),不用再使用本地文件

x_io = BytesIO()
df = pd.DataFrame(list(res['data']))
df.to_excel(x_io, sheet_name=table_name, index=False)
excel_name = table_name + '.xlsx'
response = HttpResponse()
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="%s"' % excel_name
response.write(x_io.getvalue())
return response

 

posted @ 2020-02-25 18:30  守望人间  阅读(1405)  评论(0)    收藏  举报