在django上傳和讀取xlsx文件

[英]upload and read xlsx file in django


I am using xlsx file with django for the first time. I am trying to upload a xlsx file and store its data in my models. But my function is not working

我第一次使用django的xlsx文件。我正在嘗試上傳xlsx文件並將其數據存儲在我的模型中。但我的功能不起作用

this is my views.py

這是我的views.py

def upload(request,pk):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filehandle = request.FILES.get('myfile',False)
            workbook = xlrd.open_workbook(filehandle)
            worksheet = workbook.sheet_by_index(0)
            rows = []

            for column in range(worksheet.nrows):
                for row in range(worksheet.nrows):
                    rows.append(worksheet.cell(row, column).value)
                for i in range(0,len(rows)):
                    if i==0:
                        prodatt = ProductAttribute.objects.get_or_create(name=rows[i],slug=rows[i])
                        prodatt.save()
                        rows[0]=prodatt.pk
                    elif i>=2:
                        attval = AttributeChoiceValue.objects.get_or_create(name=rows[i],slug=rows[i],attribute=rows[0])
                        print(attval)
                        attval.save()
            for i,row in range(worksheet.nrows):
                if i>1:
                    for j in row:
                        if j>0:
                            a=AttributeChoiceValue.objects.get(name=row[j]).pk
                            d={li[j-1]:a}
                            d1={**d}

                    prod = Product.objects.get_or_create(name=row[0],attributes=d1,product_type=pk)
                    print(prod)
                    prod.save()
                elif i==0:
                    li=[]
                    for j in row:
                        if j>0:
                            li.append(row[j])

        workbook.close()
        return render(request,'dashboard/list.html')

My forms.py have

我的forms.py有

class UploadFileForm(forms.Form):
    file = forms.FileField()

and my template has

我的模板有

  <form method="post" enctype="multipart/form-data" action="{%url 'dashboard:product-upload' pk=product_type.pk%}">
           {% csrf_token %}
           {{up}}
           <button type="submit">Upload</button>
       </form>

1 个解决方案

#1


0  

I used

我用了

workbook = xlrd.open_workbook(filehandle.temporary_file_path())

workbook = xlrd.open_workbook(filehandle.temporary_file_path())

in place of

代替

workbook = xlrd.open_workbook(filehandle)

and added

並補充說

FILE_UPLOAD_HANDLERS = (
    'django.core.files.uploadhandler.TemporaryFileUploadHandler',
)

in settings.py and it worked

在settings.py中,它工作


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/06/16/b3a43368f2134cc0edd1a11b2400b576.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com