Django 和 xlrd,从内存中读取

标签 django excel xlrd

我的计划是让用户上传一个Excel文件,上传后我将显示可编辑的表单,其中包含上传的Excel的内容,一旦用户确认输入正确,他/她点击保存按钮,这些项目保存在某些模型中。

为此,我编写了这个 View 和表单:

形式:

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关键字将不会被使用。

祝你编码愉快。

关于Django 和 xlrd,从内存中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3665379/

相关文章:

django - 在 IPython 中运行 Django shell

vba - Excel VBA 在 50 个工作表中运行宏

excel - 根据降序值创建列表并包含重复项

javascript - 预订/预订系统日 View ,时间粒度问题

django - create_user() 缺少 1 个必需的位置参数 : 'password'

python - 使用基于日期/时间的对象进行 Django 单元测试

excel - 将工作表保持在工作簿的首位

python - 在Python xlrd中读取Excel文件

python - 使用 Python 在 Excel 中读取合并的单元格