質問

私の計画は、ユーザーが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 この入力をどこかに保存せずにファイルから読み取りますが、どうすれば読むことができますか?

役に立ちましたか?

解決

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 キーワードは使用されません。

ハッピーコーディング。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top