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

本文介绍了一种使用Python将数据库中的数据导出为Excel文件的方法。通过定义一个函数export_excel,利用Django框架处理HTTP请求,并使用xlwt库创建Excel工作簿。该函数遍历模型字段,将每个字段名写入Excel的第一行,并从数据库中获取所有记录,将其逐条写入Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值