django admin 导出数据简单示例

借鉴博客:https://www.lijinlong.cc/django/djxs/2101.html

具体代码实现:

class TipReport(admin.ModelAdmin):
    actions = ['saveexcel']
    list_display = ('tiptype', 'enabled', 'get_tag','get_content')
    search_fields = ('get_tag', 'tiptype')
    list_per_page = 500

    def get_tag(self, obj):
        if obj.tags.all():
            tag_list = [i.name for i in obj.tags.all()]
            return ','.join(tag_list)
        else:
            return '-'

    get_tag.short_description = '小贴士标签'

    def get_content(self, obj):
        if obj.content:
            return obj.content
        elif obj.image:
            return mark_safe('<a href="%s">%s</a>' % (obj.image.url, obj.image.url))
        else:
            return '-'

    get_content.short_description = '内容'

    def saveexcel(self, request, queryset):
        Begin = xlwt.Workbook()
        sheet = Begin.add_sheet('小贴士记录')
        cols = 0
        for query in queryset:
            sheet.write(cols, 0, str(query.tiptype))
            sheet.write(cols, 1, str(query.enabled))
            # for i in unicode(query.tags.all()):
            sheet.write(cols, 2, unicode(query.tags.all()))
            print type(query.content)
            sheet.write(cols, 3, unicode(query.content))

            cols += 1

        Begin.save('{}'.format("result.xls"))
        def file_iterator(filename, chuck_size=512):
            with open(filename, 'rb') as f :
                while True:
                    c = f.read(chuck_size)
                    if c:
                        yield c
                    else:
                        break
        response = StreamingHttpResponse(file_iterator('{}'.format("result.xls")))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format("result.xls")
        return response
    saveexcel.short_description = '导出数据'
admin.site.register(Tip, TipReport)

 

转载于:https://www.cnblogs.com/haiyan123/p/9223530.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值