Python django导出excel的方法是什么
短信预约 -IT技能 免费直播动态提醒
这篇文章主要讲解了“Python django导出excel的方法是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python django导出excel的方法是什么”吧!
一、基础环境
web架构:前后端分离,前端使用vue,后端使用django 的rest framework
django版本3.2
django-excel 版本0.0.10
djangorestframework版本3.12.4
二、需求
界面导出excel数据内容
导入model包含外键类型
三、功能实现
不使用序列化类:需要手动实现外键对象转换为外键值
使用序化类:
四、源码
#models.pyfrom django.db import modelsfrom django.utils import timezoneclass MyITtype(models.Model): name = models.CharField(verbose_name="名称", max_length=128, unique=True) ittype = models.SmallIntegerField(verbose_name="类型") comment = models.TextField(verbose_name="备注", blank=True, default="") def __str__(self): return self.name class Meta: db_table = "MyITtype" verbose_name = "it资产类型"class MyAsset(models.Model): ittype = models.ForeignKey(MyITtype, on_delete=models.SET_NULL, verbose_name="产品类型", null=True) code = models.CharField(verbose_name="资产编码", max_length=128, unique=True) buytime = models.DateField(verbose_name="入仓时间", default=timezone.now) usetime = models.DateField(verbose_name="分配时间", default=timezone.now) comment = models.TextField(verbose_name="规格说明", blank=True, default="") user = models.CharField(verbose_name="使用人", max_length=128, blank=True, default="") status = models.IntegerField(verbose_name="状态") def __str__(self): return self.code class Meta: db_table = "opGTITAsset" verbose_name = "it固产"
一、序化类实现
#asset-export.pyfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.serializers import ModelSerializerfrom .models import MyAssetimport django_excel as excelclass ITAssetSer(ModelSerializer): class Meta: model = MyAsset fields = '__all__'class ITAssetExport(APIView): """""" use_model = MyAsset queryset = use_model.objects.all() serializer_class = ITAssetSer def post(self, request, *args, **kwargs): try: data = request.data id_list = data.get("data") obj_list = self.queryset.all() # 如果有值,表示导出部分,否则导出全部 if id_list: obj_list = obj_list.filter(id__in=id_list) ser = self.serializer_class(instance=obj_list, many=True) return MakeExcel(obj_list=ser.data, class_name=self.use_model, filename="itasset") except: ret = { "code": 599, "message": "导出数据出错" } return Response(ret) def get(self, request, *args, **kwargs): self.http_method_not_allowed(request, *args, **kwargs)def MakeExcel(obj_list, class_name, filename): """ 制作excel表 :param ser_list: 内容列表 :param class_name: 类名 :param filename: 文件名 :return: """ meta_fields = class_name._meta.fields name_list = [field.name for field in meta_fields] header_list = [field.verbose_name for field in meta_fields] wdata = [header_list] for obj in obj_list: data = [obj[name] for name in name_list] wdata.append(data) sheet = excel.pe.Sheet(wdata) response = excel.make_response(pyexcel_instance=sheet, file_name=filename, file_type="xlsx") return response
二、手动转换外键实现
#asset-export.pyfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.objializers import ModelSerializerfrom .models import MyAssetimport django_excel as excelclass ITAssetSer(ModelSerializer): class Meta: model = MyAsset fields = '__all__'class ITAssetExport(APIView): """""" use_model = MyAsset queryset = use_model.objects.all() objializer_class = ITAssetSer def post(self, request, *args, **kwargs): try: obj_list = self.use_model.objects.all() return MakeExcel(obj_list=obj_list, class_name=self.use_model, filename="itasset") except: ret = { "code": 599, "message": "导出数据出错" } return Response(ret) def get(self, request, *args, **kwargs): self.http_method_not_allowed(request, *args, **kwargs)def MakeExcel(obj_list, class_name, filename): """ 制作excel表 :param obj_list: 内容列表 :param class_name: 类名 :param filename: 文件名 :return: """ meta_fields = class_name._meta.fields name_list = [field.name for field in meta_fields] header_list = [field.verbose_name for field in meta_fields] wdata = [header_list] for obj in obj_list: data = [] for name in name_list: value = eval("obj." + name) # 等价于getattr(obj,name),即获取该对象某个字段内容 if isinstance(value, Model): value = eval("".join(["obj." + name + "_id"])) # 等价于obj.name_id,即获取该对象中外键对象数值 data.append(value) # 参考例子 # data = [getattr(obj, name) if name != "ittype" else obj.ittype_id for name in name_list] wdata.append(data) sheet = excel.pe.Sheet(wdata) response = excel.make_response(pyexcel_instance=sheet, file_name=filename, file_type="xlsx") return response
感谢各位的阅读,以上就是“Python django导出excel的方法是什么”的内容了,经过本文的学习后,相信大家对Python django导出excel的方法是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341