После загрузки и открытия файла excel он показывает мне ошибку (Django, python)

Вот мой view.py код :

def downloadfile(request, filename=''):
  if filename != '':
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = 'SampleExcel.xls'
    filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" 
    path = open(filepath, encoding='cp437')
    mime_type, _ = mimetypes.guess_type(filepath)
    response = HttpResponse(path, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    return response
  else:
    return HttpResponseRedirect("adduser", {})

Файл загружается правильно, но не открывается, как показано на следующих изображениях.

enter image description here

enter image description here

Используйте FileResponse вместо этого:

  if filename != '':
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = 'SampleExcel.xls'
    filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" 
    with open(filepath, 'rb') as path:
        return FileResponse(path, True, filename)
  else:
    return HttpResponseRedirect("adduser", {})

Вы можете убедиться, что добавили 'rb' в open('Sample.xls', 'rb')

def downloadfile(request, filename=''):
  if filename != '':
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = 'SampleExcel.xls'
    filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" 
    path = open(filepath, 'rb')
    mime_type, _ = mimetypes.guess_type(filepath)
    response = HttpResponse(path, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    return response
 else:
    return HttpResponseRedirect("adduser", {})

Это решит вашу проблему.

Вернуться на верх