python - Django 导入 Excel 端点

标签 python django import-from-excel

我正在尝试创建一个端点,用于将 Excel 文件加载到服务器中并导入其中的数据。 为此,我使用 django-import-export包裹。 这是查看代码:

    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)

将文件加载到(tablib)数据集中时,我收到此错误:

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

我尝试引用文件名,因此替换

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

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

然后数据集似乎确实加载了文件,因为在响应中我看到了文件的一些字节表示,但我也收到了此错误消息:

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

有什么想法吗?

更新: 我的 ItemImportModel 模型:

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)

我尝试导入的文件: enter image description here

最佳答案

主要问题是 dataset.load 部分。 显然对于不同类型的文件应该有不同的处理。
这最终对我有用

对于 csv-

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

对于 xls-

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

对于 xlsx -

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

关于python - Django 导入 Excel 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732647/

相关文章:

python - BeautifulSoup 只需提取表头

python - Cbv View 对象在django中没有属性 'object'

java - 将 POI RichTextString 转换为 HTML 或 RTF

Python 从 .xls 文件读取数据时出错

python - 为什么Python既有格式函数又有格式方法

python - 稀疏矩阵 : how to get nonzero indices for each row

javascript - Django/Ajax/Jquery 在同一事件中运行两个 ajax 请求。

java - Apache POI 跳过从未更新过的行

Python TypeError : must be string, 不是 int

python - 如何在不更改 python 代码的情况下将 "print"命令输出重定向到文件?