希望用户能够将数据导出为.csv。
当用户:
会发生什么:
现在的问题是: 我想要“导出到Excel”按钮,从Django项目的根目录下载生成的文件。
这是按钮:
app/views.py
这是def export(request):
filename = "test.csv" # this is the file people must download
response['Content-Disposition'] = 'attachment; filename=' + filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
return response
:
app/urls.py
这是# app/urls.py
from django.conf.urls import url
from . import views
# Create your urls here.
urlpatterns = [
(...)
url(r'^export/$', views.export, name='export')
]
:
{{1}}
问题是:如何让用户使用按钮导出文件?我做错了什么?
提前感谢您的帮助/指导
方便的链接:
答案 0 :(得分:2)
您必须先创建response
对象才能为其分配标题。
def export(request):
filename = "test.csv" # this is the file people must download
with open(filename, 'rb') as f:
response = HttpResponse(f.read(), content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=' + filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
return response