通过django admin将excel数据导入模型

RdB*_*RdB 8 python django xls django-admin

我需要Django Admin界面来接受Excel文件的管理员上传,其中每个Excel文件中的数据都插入到我的数据库模型中.如何在Django模型管理页面上显示这样的"上传"按钮,点击该按钮要求管理员选择一个.xls文件,一旦上传完成,该数据的数据会被添加到数据库中?

wob*_*col 7

我已经完成了这个,但我只是设置了一个带文件上传的简单视图(实际上这比将它直接添加到Django管理页面更有意义,因为一个编辑页面=一个模型实例,我认为你的excel包含多个楷模).

在forms.py中,一个带有文件上载字段的简单表单

class ImportExcelForm(forms.Form):
    file  = forms.FileField(label= "Choose excel to upload")    
Run Code Online (Sandbox Code Playgroud)

在views.py中,一个处理上传的视图

def test_flowcell(request):
    c = RequestContext(request, {'other_context':'details here'})
    if request.method == 'POST': # If the form has been submitted...
        form = ImportExcelForm(request.POST,  request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            excel_parser= ExcelParser()
            success, log  = excel_parser.read_excel(request.FILES['file'] )
            if success:
                return redirect(reverse('admin:index') + "pages/flowcell_good/") ## redirects to aliquot page ordered by the most recent
            else:
                errors = '* Problem with flowcell * <br><br>log details below:<br>' + "<br>".join(log)
                c['errors'] = mark_safe(errors)
        else:
            c['errors'] = form.errors 
    else:
        form = ImportExcelForm() # An unbound form
    c['form'] = form
    return render_to_response('sequencing/file_upload.html')
Run Code Online (Sandbox Code Playgroud)

并且正如在另一篇文章中所建议的那样,使用xlrd从excel文件中读取数据.我有一个单独的文件ExcelParser.py

import xlrd 

class ExcelParser(object, excel_name):
    @transaction.commit_on_success        
    def read_excel(self):
        wb = xlrd.open_workbook(excel_name)

        ...
        do your parsing in here.....
        ...
Run Code Online (Sandbox Code Playgroud)

(我可以补充一点,excel是一种非常糟糕且容易出错的导入数据的方法.我在工作中做了很多工作,并试图说服管理层有更好的解决方案.)


And*_*ker 4

我不确定 Django 方面的情况,但您可以使用xlrd读取和操作 Excel 文件。有一个免费的 PDF 解释了这一点,称为“在 Python 中使用 Excel 文件”