Django 和 xlrd,从内存中读取
我的计划是让用户上传一个excel文件,上传后我将显示可编辑的表单,其中包含上传的excel的内容,一旦用户确认输入正确,他/她点击保存按钮,这些项目就会被保存在某些模型上。
为此,我编写了以下视图和表单:
form:
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
view:
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})
正如您在 # 中看到的,我需要使用 input_excel.open_workbook( 打开此 input_excel )
我需要从内存中读取,但是 open_workbook
从文件中读取,而不将此输入保存到某个地方,我该如何读取它?
My plan is to let a user to upload an excel file, once uploaded I will be displaying editable form which contains the content of the uploaded excel, once user confirms the input is correct, he/she hits the save button and these items are saved at some model.
For this, I have written this view and form:
form:
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
view:
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})
As you can see at the # I need to open this input_excel with input_excel.open_workbook()
I need to read from memory but open_workbook
reads from a file, without saving this input to somewhere, how can I read it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当提供
file_contents
可选关键字时,filename
关键字将不会被使用。快乐编码。
When
file_contents
optional keyword is provided,filename
keyword will not be used.Happy Coding.