背景
django项目实现一个对数据库数据导出excel并提供给用户下载xlsx的功能
代码
from io import BytesIO
from django.utils.http import urlquote
import pandas as pd
from django.http import HttpResponse
def download_xlsx():
data = [[1,2,3],[4,5,6]]
bio = BytesIO()
with pd.ExcelWriter(bio, engine='openpyxl') as writer:
pd.DataFrame(data).to_excel(writer, encoding="utf-8")
bio.seek(0)
response = HttpResponse(bio, content_type='application/vnd.ms-excel')
file_name = urlquote('data.xlsx')
response['Content-Disposition'] = 'attachment; filename=%s' % file_name
return response