Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method for Python django to export excel

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Python django export excel method is what", the explanation content in the article is simple and clear, easy to learn and understand, please follow the small series of ideas slowly in-depth, together to study and learn "Python django export excel method is what"!

I. Basic environment

Web architecture: front-end separation, front-end use vue, back-end use django rest framework

django version 3.2

django-excel version 0.0.10

djangorestframework version 3.12.4

II. Demand

Interface export excel data content

Import model contains foreign key type

III. Function realization

1. Do not use serialization classes: manual conversion of foreign key objects to foreign key values is required

2. Use the sequencing class:

Source code #models.pyfrom django.db import modelsfrom django.utils import timezoneclass MyITtype(models.Model): name = models.CharField(verbose_name="name", max_length=128, unique=True) ittype = models.SmallIntegerField(verbose_name="type") comment = models.TextField(verbose_name="Note", blank=True, default="") def __str__(self): return self.name class Meta: db_table = "MyITtype" verbose_name = "it Asset type"class MyAsset(models.Model): ittype = models.ForeignKey(MyITtype, on_delete=models.SET_NULL, verbose_name="Product Type," null=True) code = models.CharField(verbose_name="Asset Code", max_length=128, unique=True) buytime = models.DateField(verbose_name="timezone.now") usetime = models.DateField(verbose_name="allocate time," default=timezone.now) comment = models.TextField(verbose_name="Specifications", blank=True, default="") user = models.CharField(verbose_name="User", max_length=128, blank=True, default="") status = models. IntegrField (verbose_name="Status") def __str__(self): return self.code class Meta: db_table = "opGTITAsset" verbose_name = "it fixed production" I. Sequencing class implementation #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 there is a value, it means to export part, otherwise export 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": "Error exporting data" } return Response(ret) def get(self, request, *args, **kwargs): self.http_method_not_allowed(request, *args, **kwargs)def MakeExcel(obj_list, class_name, filename): """ Create excel sheets :param ser_list: Content list :param class_name: Class name :param filename: 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 II. Manually convert foreign key implementations #asset-export.pyfrom rest_framework.views import APIViewfrom rest_framework.response import Response from rest_framework. objecizers 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": "Error exporting data" } return Response(ret) def get(self, request, *args, **kwargs): self.http_method_not_allowed(request, *args, **kwargs)def MakeExcel(obj_list, class_name, filename): """ Create excel sheets :param obj_list: Contents list :param class_name: Class name :param filename: 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) #Equivalent to getattr(obj,name), i.e. get the content of a field of the object if isinstance(value, Model): value = eval("".join(["obj. " + name + "_id"]) #Equivalent to obj.name_id, i.e. get the value of foreign key object in this object data.append(value) #Reference example # 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 Thank you for reading, the above is the content of "Python django export excel method is what", after learning this article, I believe that everyone on Python django export excel method is what this problem has a deeper understanding, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report