简体   繁体   中英

Django Import Excel Endpoint

I'm trying to create an endpoint for loading an excel file into server and importing the data in it. To do it I'm using django-import-export package. This is the view code:

    def create(self, request, *args, **kwargs):
    file_serializer = self.get_serializer(data=request.data)
    file_serializer.is_valid(raise_exception=True)
    if file_serializer.is_valid():
        from tablib import Dataset
        from workflows.submittals.admin import ItemImportResource
        item_model_resource = ItemImportResource()
        file_serializer.save()
        dataset = Dataset()
        file_obj = request.FILES['file']

        imported_data = Dataset().load(open(file_obj).read())

        result = item_model_resource.import_data(dataset, dry_run=True) 
        if not result.has_errors():
            item_model_resource.import_data(dataset, dry_run=False)  

        return Response(file_serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

When loading the file into the (tablib) Dataset, I'm getting this error:

'invalid file: <InMemoryUploadedFile: Import_Sample_test1.xls (application/vnd.ms-excel)>'

I tried reffering the name of the file, so replaced

imported_data = Dataset().load(open(file_obj).read())

with

imported_data = Dataset().load(open(file_obj.name).read())

Then it seems like the Dataset does loads the file, because in the response I see some byte representation of the file, but I also get this error message:

'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

Any idea?

UPDATE: my ItemImportModel model:

class ItemImportModel(models.Model):

spec_section_identifier = models.CharField('Spec Section #', max_length=15)
spec_section_name = models.CharField('Spec Section Name',max_length=200)
sub_spec_section = models.CharField('Sub Spec Section', max_length=200, null=True, blank=True)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True, default="")
type = models.CharField(max_length=50, choices=Item.ITEM__TYPES)

file I'm trying to import: 在此处输入图片说明

The main issue was the dataset.load part. Apparently there should be different handling for different types of file.
This what finally worked for me

for csv-

imported_data = dataset.load(open(file_obj.name).read())

for xls-

imported_data = dataset.load(open(file_obj.name, 'rb').read(), 'xls')

for xlsx -

imported_data = dataset.load(open(file_obj.name, 'rb').read(), 'xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM