Tia*_*ica 1 python csv django excel reddit
所以,这是我用 Django 1.8 创建 atm 的网页:

希望用户能够将数据导出为 .csv。
当用户:
发生什么了:
现在的问题是: 我想要带有“导出到 Excel”的按钮,从 Django 项目的根目录下载生成的文件。
这是按钮:
<form class="export_excel" id="login_form" action="/app/export">
{% csrf_token %}
<button class="btn btn-lg btn-primary btn-block" value="Export to Excel" type="submit">Export To Excel</button>
</form>
Run Code Online (Sandbox Code Playgroud)
这是在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
Run Code Online (Sandbox Code Playgroud)
这是在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')
]
Run Code Online (Sandbox Code Playgroud)
问题是:如何让用户使用按钮导出文件?我究竟做错了什么?
预先感谢您的帮助/指导
方便的链接:
您必须首先创建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
Run Code Online (Sandbox Code Playgroud)
取自这里