Django et xlrd, la lecture de la mémoire
Question
Mon plan est de permettre à un utilisateur de télécharger un fichier Excel, une fois téléchargé, j'exposerons forme modifiable qui contient le contenu de l'Excel, une fois confirme utilisateur téléchargé l'entrée est correcte, il / elle frappe le bouton Enregistrer et ceux-ci éléments sont enregistrés à un modèle.
Pour cela, je l'ai écrit ce point de vue et de la forme:
forme:
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
vue:
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})
Comme vous pouvez le voir à la # I need to open this input_excel with input_excel.open_workbook()
que je dois lire de la mémoire mais open_workbook
lit à partir d'un fichier, sans enregistrer cette entrée quelque part, comment puis-je lire?
La solution
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})
Lorsque file_contents
en option mot-clé est fourni, mot-clé filename
ne sera pas utilisé.
Bonne programmation.