gpt4 book ai didi

django - 在 Django 中上传和读取 xlsx 文件

转载 作者:行者123 更新时间:2023-12-01 14:35:57 27 4
gpt4 key购买 nike

我第一次在 django 中使用 xlsx 文件。我正在尝试上传一个 xlsx 文件并将其数据存储在我的模型中。但我的功能不起作用

这是我的 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')

我的 forms.py 有
class UploadFileForm(forms.Form):
file = forms.FileField()

我的模板有
  <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>

最佳答案

我用了
workbook = xlrd.open_workbook(filehandle.temporary_file_path())
代替

workbook = xlrd.open_workbook(filehandle)

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

在 settings.py 中,它起作用了

关于django - 在 Django 中上传和读取 xlsx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885103/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com