Django数据导出excel文件

需要安装pip install xlwt
def export_book(request):
    bookinfo = Books.objects.all()
    if bookinfo:
        # 设置语言,建议是utf-8因为需要中文支持
        language = Workbook(encoding='utf-8')
        # 创建excel表
        w = language.add_sheet(u"sheet1")
        w.write(0, 0, "ID编号")
        w.write(0, 1, u"图书种类")
        w.write(0, 2, u"图书名称")
        w.write(0, 3, u"入库几册")
        w.write(0, 4, u"图书国籍")
        w.write(0, 5, u"是否入库")
        w.write(0, 6, u"图书价格")
        w.write(0, 7, u"添加时间")
        w.write(0, 8, u"上传图片名称")
        # 写入数据
        excel_row = 1
        for obj in bookinfo:
            data_id = obj.booksid
            data_species = obj.booksspecies
            data_name = obj.booksname
            data_number = obj.booksnumber
            dada_country = obj.bookscountry
            dada_storage = obj.booksstorage
            dada_money = obj.booksmoney
            dada_times = obj.bookstimes
            dada_img_name = obj.booksimg_name
            w.write(excel_row, 0, data_id)
            w.write(excel_row, 1, data_species)
            w.write(excel_row, 2, data_name)
            w.write(excel_row, 3, data_number)
            w.write(excel_row, 4, dada_country)
            w.write(excel_row, 5, dada_storage)
            w.write(excel_row, 6, dada_money)
            w.write(excel_row, 7, dada_times)
            w.write(excel_row, 8, dada_img_name)
            excel_row += 1
        # 保存文件
        exist_file = os.path.exists("export_info.xls")
        if exist_file:
            os.remove(r"export_info.xls")
        language.save("export_info.xls")
        # 这里使用io流.
        ioa = BytesIO()
        language.save(ioa)
        ioa.seek(0)
        response = HttpResponse(ioa.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=export_info.xls'
        response.write(ioa.getvalue())
        return response
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值