如何解决 excel 上传到模型时的 XLRD 错误

How to solve XLRD error on excel upload to a model

这是我从尝试将 excel 数据文件上传到 Django 模型的视图中得到的错误。

Traceback (most recent call last):
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Python\Django\Links Online Exams\Links_Online_Results\teachers\views.py", line 106, in UploadTeacherView
    book = xlrd.open_workbook(path)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\__init__.py", line 172, in open_workbook
    bk = open_workbook_xls(
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 79, in open_workbook_xls
    biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1284, in getbof
    bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1278, in bof_error
    raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'code,fir'
[05/Apr/2021 22:54:31] "POST /teachers/upload HTTP/1.1" 500 87102

下面是我试图从中得出的观点。我实际上一直无法找到解决此问题的正确方法。我相信我们中的某个人一定在一个或多个实例中发现了这个错误。

def UploadTeacherView(request):
    message=''
    
    if request.method == 'POST':
        form = NewTeachersForm(request.POST, request.FILES)
        if form.is_valid():
            excel_file = request.FILES['file']
            fd, path = tempfile.mkstemp()
            try:
                with os.fdopen(fd, 'wb') as tmp:
                    tmp.write(excel_file.read())
                book = xlrd.open_workbook(path)
                print(book)
                sheet = book.sheet_by_index(0)
                obj=TeacherData(
                    code = sheet.cell_value(rowx=1, colx=1),
                    first_name = sheet.cell_value(rowx=2, colx=1),
                    last_name = sheet.cell_value(rowx=3, colx=1),
                    email = sheet.cell_value(rowx=4, colx=1),
                    phone = sheet.cell_value(rowx=5, colx=1),

                )
                obj.save()
            finally:
                os.remove(path)
        else:
            message='Invalid Entries'
    else:
        form = NewTeachersForm()
    return render(request,'new_teacher.html', {'form':form,'message':message})

经过@DeepSpace 的提示,我上传.xls files.

解决了问题