سؤال

تتمثل خطتي في السماح للمستخدم بتحميل ملف 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