26

我的计划是让用户上传一个excel文件,一旦上传,我将显示包含上传的excel内容的可编辑表单,一旦用户确认输入正确,他/她点击保存按钮并保存这些项目在某些模型。

为此,我写了这个视图和表单:

形式:

IMPORT_FILE_TYPES = ['.xls', ]

class XlsInputForm(forms.Form):
    input_excel = forms.FileField(required= True, label= u"Upload the Excel file to import to the system.")

    def clean_input_excel(self):
        input_excel = self.cleaned_data['input_excel']
        extension = os.path.splitext( input_excel.name )[1]
        if not (extension in IMPORT_FILE_TYPES):
            raise forms.ValidationError( u'%s is not a valid excel file. Please make sure your input file is an excel file (Excel 2007 is NOT supported.' % extension )
        else:
            return input_excel

看法:

def import_excel_view(request):
    if request.method == 'POST':
        form = XlsInputForm(request.POST, request.FILES)
        if form.is_valid():
            input_excel = request.FILES['input_excel']
            # I need to open this input_excel with input_excel.open_workbook()
            return render_to_response('import_excel.html', {'rows': rows})
    else:
        form = XlsInputForm()

    return render_to_response('import_excel.html', {'form': form})

正如您在# I need to open this input_excel with input_excel.open_workbook()我需要从内存open_workbook中读取但从文件中读取的那样,如果不将此输入保存到某处,我该如何读取它?

4

1 回答 1

71
if form.is_valid():
    input_excel = request.FILES['input_excel']
    book = xlrd.open_workbook(file_contents=input_excel.read())

    # your work with workbook 'book'

    return render_to_response('import_excel.html', {'rows': rows})

file_contents提供可选关键字时,filename将不使用关键字。

快乐编码。

于 2010-09-08T07:57:14.663 回答