Domanda

Il mio piano è quello di consentire a un utente di caricare un file di Excel, una volta caricato mi esporrà forma modificabile che contiene il contenuto della Excel caricato, una volta conferma utente l'input è corretto, lui / lei preme il pulsante e questi Salva articoli vengono salvati ad un certo modello.

Per questo, ho scritto questo punto di vista e la forma:

forma:

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

Visualizza:

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})

Come si può vedere al # I need to open this input_excel with input_excel.open_workbook() ho bisogno di leggere dalla memoria ma open_workbook legge da un file, senza salvare questo ingresso da qualche parte, come posso leggerlo?

È stato utile?

Soluzione

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})

Quando file_contents opzionale parola chiave è previsto, non sarà usata filename parola chiave.

Happy Coding.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top