def export_to_excel(request):
lists = MyModel.objects.all()
# your excel html format
template_name = "sample_excel_format.html"
response = render_to_response(template_name, {'lists': lists})
# this is the output file
filename = "model.csv"
response['Content-Disposition'] = 'attachment; filename='+filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
return response
Run Code Online (Sandbox Code Playgroud)
from django.conf.urls.defaults import *
urlpatterns = patterns('app_name.views',
url(r'^export/$', 'export_to_excel', name='export_to_excel'),
)
Run Code Online (Sandbox Code Playgroud)
<a href="{% url app_name:export_to_excel %}">Export</a>
Run Code Online (Sandbox Code Playgroud)
什么都没有获取文件选项下载,没有给出任何错误,但我可以看到所有结果在日志中工作正常.
小智 7
我认为导出excel文件的解决方案是:
if 'excel' in request.POST:
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=Report.xlsx'
xlsx_data = WriteToExcel(weather_period, town)
response.write(xlsx_data)
return response
Run Code Online (Sandbox Code Playgroud)
在此示例中,用于导出的库是xlsxWriter.这是一个非常完整和实用的解决方案,以及许多其他解决方案:http://assist-software.net/blog/how-export-excel-files-python-django-application.