视图.py
def contact_list(request):
importform = ImportExcelForm()
if request.method == 'POST':
importform = ImportExcelForm(request.POST, request.FILES)
if importform.is_valid():
input_excel = request.FILES['input_excel']
book = xlrd.open_workbook(file_contents=input_excel.read())
excel_parser= ExcelParser()
success, log = excel_parser.read_excel(request.FILES['input_excel'] )
return redirect('/member/incident-types/')
else:
importform = ImportExcelForm()
return render(request, 'incident/contact_list.html',
{
'about_menu': True,
'ImportExcelForm':importform,
})
表格.py
class ImportExcelForm(Form):
input_excel = forms.FileField()
user = forms.ModelChoiceField(queryset=Contacts.objects.all())
def save(self):
records = xls.reader(self.cleaned_data["input_excel"])
for line in records:
input_data = Data()
input_data.place = self.cleaned_data["user"]
input_data.name = line[1]
input_data.number = line[2]
input_data.save()
模型.py
class Contacts(models.Model):
user = models.ForeignKey(User, null=True)
name = models.CharField('Name', max_length=100)
number = models.IntegerField()
这是导入 xls 文件,读取 xls 文件中的姓名和联系电话并将其写入数据库字段。我没有收到任何错误,但它没有解析数据库中的数据。