Вопрос

Мой план - позволить пользователю загрузить файл 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