如何将excel文件导入到django中的表中

问题描述 投票:0回答:1

我有这个模型来存储有关计算机的信息。 我正在尝试添加一个功能来直接导入包含数据的 Excel 文件,而不是在表格中输入数据,以防有大量数据需要输入。

模型.py

class Product(models.Model):
    
    model=models.CharField(max_length=50, null=True)
    serial=models.CharField(max_length=50, null=True)
    hd_size=models.CharField(max_length=50,null=True)
    ram=models.CharField(max_length=50, null=True)
    processor=models.CharField(max_length=50, null=True)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.serial + ' - ' + self.model

视图.py

@login_required
def product_mgt(request):
    context['page_title'] = "Computer List"
    products = Product.objects.all()
    context['products'] = products

    return render(request, 'product_mgt.html', context)

表格.py

class SaveProduct(forms.ModelForm):
    model= forms.CharField(max_length=50,)
    serial= forms.CharField(max_length=50, )
    hd_size= forms.CharField(max_length=50, )
    ram= forms.CharField(max_length=50, )
    processor= forms.CharField(max_length=50, )

    class Meta:
        model = Product
        fields = ('model','serial','hd_size','ram', 'processor')

    def clean_serial(self):
        id = self.instance.id if self.instance.id else 0
        serial = self.cleaned_data['serial']
        try:
            if int(id) > 0:
                product = Product.objects.exclude(id=id).get(serial = serial)
            else:
                product = Product.objects.get(serial = serial)
        except:
            return serial
        raise forms.ValidationError(f"{serial} Computer Already Exists.")
python django django-models django-views django-forms
1个回答
0
投票

哟。我实际上在几周前使用这段代码解决了这个问题

def import_product(request):
    if request.method == 'POST':
        excel_file = request.FILES['excel_file']
        wb = openpyxl.load_workbook(excel_file)
        ws = wb.active

        for row in ws.iter_rows(min_row=2, values_only=True):
            model, serial, hd_size, ram, processor = row
            Product.objects.create(model= model, serial= serial, hd_size= hd_size, ram= ram, processor= processor)

        return render(request, 'import_success_2.html')

    return render(request, 'import_product.html')

def import_success_2(request):
    return render(request, 'computers/import_success_2.html')

我也做了:pip install openpyxl

然后我创建了两个模板:import_product 和 success

导入产品.html

<p style="color:whitesmoke;font-size:20px;">
    Select a file containing the Computers you want to Import
  </p>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="excel_file">
    <button type="submit">Import</button>
</form>

<div class="container-fluid">
    <button onclick="goBack()">Go Back</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.