将Excel文件上载到Django时出现属性错误

将Excel文件上载到Django时出现属性错误,django,excel,python-3.x,file-upload,Django,Excel,Python 3.x,File Upload,我无法将excel文件上载到django应用程序。这是一个非常简单的应用程序,应该允许用户上传一个包含3列的excel文件。应用程序将读取此文件的内容并将其处理为一系列计算 这是我的表格。py: class InputForm(forms.Form): FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"})) FILE_U

我无法将excel文件上载到django应用程序。这是一个非常简单的应用程序,应该允许用户上传一个包含3列的excel文件。应用程序将读取此文件的内容并将其处理为一系列计算

这是我的表格。py

class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
                    "django_excel.TemporaryExcelFileUploadHandler"]
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
     if request.method == 'POST':
        form = InputForm(request.POST,request.FILES['FileLocation'])


     if form.is_valid():
         book = xlrd.open_workbook(request.FILES('FileLocation'))
         for sheet in book.sheets():
             number_of_rows = sheet.nrows
             number_of_columns = sheet.ncols
             print(number_of_rows)
设置.py

class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
                    "django_excel.TemporaryExcelFileUploadHandler"]
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
     if request.method == 'POST':
        form = InputForm(request.POST,request.FILES['FileLocation'])


     if form.is_valid():
         book = xlrd.open_workbook(request.FILES('FileLocation'))
         for sheet in book.sheets():
             number_of_rows = sheet.nrows
             number_of_columns = sheet.ncols
             print(number_of_rows)
视图.py

class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
                    "django_excel.TemporaryExcelFileUploadHandler"]
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
     if request.method == 'POST':
        form = InputForm(request.POST,request.FILES['FileLocation'])


     if form.is_valid():
         book = xlrd.open_workbook(request.FILES('FileLocation'))
         for sheet in book.sheets():
             number_of_rows = sheet.nrows
             number_of_columns = sheet.ncols
             print(number_of_rows)
我上传了表单中的文件,它给了我一个错误:

    AttributeError at /app/analyze/

    'ExcelInMemoryUploadedFile' object has no attribute 'get'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/data/analyze/
Django Version:     1.11
Exception Type:     AttributeError
Exception Value:    

Exception Location:     C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
    Python Executable:  C:\Python36\python.exe
    Python Version:     3.6.4
我还能够使用以下views.py代码成功上载.csv文件:

def analyze(request):
    c={}
    context = RequestContext(request)
    c.update(csrf(request))
    abc=['a','b','c']
    if request.method == 'POST':
        form = InputForm(request.POST,request.FILES)
        dataType = request.POST.get("DataType")
        print(dataType)
        if form.is_valid():
            cd = form.cleaned_data            #print (cd)

            a =  TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')

        #print (request.FILES.keys())
        data = csv.reader(a)
        row1csv = next(data)
        region = row1csv[0]
        metric = row1csv[2]

我试过django excel,但也有同样的错误

您正确地初始化了.CSV格式的表单,但Excel格式的表单初始化不正确:

form = InputForm(request.POST, request.FILES)
不要使用
request.FILES['FileLocation']
初始化,因为这样会将错误的类型传递给表单。它期望上传文件的多值dict,而不是单个上传文件。这就是它在调用
get
时失败的原因

接下来,您不能将
ExcelInMemoryUploadedFile
传递给
xlrd.get\u工作簿()
。您需要先将文件保存到磁盘,然后将其路径传递到
get\u workbook()
方法。django excel提供了一些更简单的方法:

book = request.FILES['FileLocation'].get_book()  # note the square brackets!
或直接访问图纸:

sheet = request.FILES['FileLocation'].get_sheet('sheet1')

我认为显示
InputForm
的代码会有帮助,似乎这就是问题所在。而且这个代码是错误的:
book=xlrd.open_工作簿(request.FILES('FileLocation'))
,它应该是
request.FILES['FileLocation']
的方括号。但这是另一个错误,它不会在表单的小部件中产生错误。感谢您的审阅。(1) 你是说InputForm的HTML代码吗?(2) 我尝试将语句中的代码更改为
request.FILES['FileLocation']
。相同的错误。是的,正如我所说的,您的错误与方括号无关,但是在修复第一个错误后,您会得到一个新错误:-)对不起,我的错,错过了顶部的
InputForm
代码。您没有正确初始化表单:
form=InputForm(request.POST,request.FILES['FileLocation'))
应该是
form=InputForm(request.POST,request.FILES)
。这里需要的是字典(QueryDict),而不是上传的文件。我在
request.FILES
中尝试了这种更改。我遇到了下一个错误:
应该是str、bytes或os.PathLike对象,而不是MultiValueDict
什么??真奇怪。它在哪一行给出这个错误?你能显示完整的痕迹吗?我希望在代码中的其他位置会出现这样的错误,可能是
book=xlrd.open\u工作簿(request.FILES['FileLocation'])
line
book=xlrd.open\u工作簿(request.FILES)C:\Python36\lib\site packages\xlrd\\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu作为f:
我认为错误在
xlrd.openworkbook
文件内容文件名{'FileLocation':}
xlrd.open\u工作簿()
需要一个路径或字节流,您不能将
请求.FILES
请求.FILES['FileLocation']
传递给它。检查xlrd的文档。将文件保存到首先上载的磁盘,然后将文件路径传递到
xlrd。打开\u workshop()
。对于
ExcelMixin
,似乎有一个函数
get_book()
get_sheet()
,这样您就可以直接在上载的文件对象上获取
book=request.FILES['FileLocation']文件。get_book()
。看见