Python 把数据库的数据导出到excel表

import io,xlwt
def export_excel(request):
    """导出数据到excel表"""
    list_obj = models.Asset._meta.get_fields()
    list_data = models.Asset.objects.all().values()
    if list_obj:
        ws = xlwt.Workbook()
        w = ws.add_sheet("这是第一页")
        for i, j in zip(range(len(list_obj)), list_obj):
            # print(i,j.__dict__["_verbose_name"])
            w.write(0, i, j.__dict__["_verbose_name"])
        excel_row = 1
        for obj_d in list_data:
            for i, obj in zip(range(len(list_obj)), list_obj):
                row = obj.__dict__["name"]
                w.write(excel_row, i, obj_d[row])
            excel_row += 1
        sio = io.BytesIO()
        # print(sio)
        ws.save(sio)
        sio.seek(0)
        response = HttpResponse(sio.getvalue(), content_type='application/octet- stream')
        response['Content-Disposition'] = 'attachment; filename=test.xls'
        response.write(sio.getvalue())
        return response
    else:
        return HttpResponse("没有数据")

转载于:https://www.cnblogs.com/wspblog/p/7151371.html

你可能感兴趣的:(Python 把数据库的数据导出到excel表)