zoukankan      html  css  js  c++  java
  • 基于 Django admin 通过后台导出

    from django.http import HttpResponse
    from openpyxl import Workbook
    
    
    class ExportExcelMixin:
        '''
        通用导出 Excel 文件动作
        '''
    
        def export_as_excel(self, request, queryset):
            '''
            导出为 excel 文件. 文件名为 app名.模型类名.xlsx.
    
            :param request:
            :param queryset:
            :return:
            '''
            # 用于定义文件名, 格式为: app名.模型类名
            meta = self.model._meta
            # 模型所有字段名
            field_names = [field.name for field in meta.fields]
            field_verbose_names = [field.verbose_name for field in meta.fields]
    
            # 定义响应内容类型
            response = HttpResponse(content_type='application/msexcel')
            # 定义响应数据格式
            response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'
    
            wb = Workbook()
            ws = wb.active
            ws.append(field_verbose_names)
    
            # 遍历选择的对象列表
            for obj in queryset:
                # 将模型属性值的文本格式组成列表
                data = []
                for field in field_names:
    
                    if hasattr(obj, f'get_{field}_display'):
                        # 可选属性取显示的值
                        value = getattr(obj, f'get_{field}_display')()
                    else:
                        value = getattr(obj, field)
    
                    data.append(f'{value}')
    
                ws.append(data)
    
            # 将数据存入响应内容
            wb.save(response)
    
            return response
    
        # 该动作在 admin 中的显示文字
        export_as_excel.short_description = '导出Excel'
    
  • 相关阅读:
    java 配置Apache,Tomcat的gzip压缩功能
    java并发编程中CountDownLatch和CyclicBarrier的使用
    Java常用工具包 Jodd
    Servlet 3特性:异步Servlet
    tomcat7安装
    2013-Hessian
    使用commons configuration管理配置文件
    2013-JVisualVM远程监听服务器内存进程
    Jquery复选框
    Jquery选择器总结
  • 原文地址:https://www.cnblogs.com/YQYC/p/14261312.html
Copyright © 2011-2022 走看看