如何使用excel格式导出python中的数据?

Ash*_*ena 5 python django

views.py

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)

urls.py

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)
  1. 最后,在您的页面中创建一个指向导出的按钮或链接.

page.html中

<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.


jmc*_*ara 4

除了其他答案中显示的选项之外,您还可以使用XlsxWriter创建 Excel 文件。

请参阅此示例