本文目录


    Django实用技巧:如何把数据导出到Excel

    将数据导出到XLS文件 如果您确实需要导出到.xls文件,请使用这个方法。你将能够添加格式为粗体字体、字体大小、定义列大小等。

    首先,安装xlwt模块。最简单的方法是使用pip。

    pip install xlwt

    views.py内容:

    import xlwt
    from django.http import HttpResponse
    from django.contrib.auth.models import User
    def export_users_xls(request):
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="users.xls"'
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('Users')
        # Sheet header, first row
        row_num = 0
        font_style = xlwt.XFStyle()
        font_style.font.bold = True
        columns = ['Username', 'First name', 'Last name', 'Email address', ]
        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)
        # Sheet body, remaining rows
        font_style = xlwt.XFStyle()
        rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
        for row in rows:
            row_num += 1
            for col_num in range(len(row)):
                ws.write(row_num, col_num, row[col_num], font_style)
        wb.save(response)
        return response

    urls.py内容:

    import views
    urlpatterns = [
        ...
        url(r'^export/xls/$', views.export_users_xls, name='export_users_xls'),
    ]

    template.html 内容:

    <a href="{% url 'export_users_xls' %}">Export all users</a>

    原文链接:https://www.django.cn/article/show-9.html