我第一次使用带有django的xlsx文件。我正在尝试上传xlsx文件并将其数据存储在我的模型中。但我的功能不起作用
这是我的views.py
setStyle("hover:-fx-background-color: #101010");
我的forms.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')
我的模板有
class UploadFileForm(forms.Form):
file = forms.FileField()
答案 0 :(得分:0)
我用过
workbook = xlrd.open_workbook(filehandle.temporary_file_path())
取代
workbook = xlrd.open_workbook(filehandle)
并添加了
FILE_UPLOAD_HANDLERS = (
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
)
在settings.py中并且它有效