2012-04-02 102 views
8

我需要Django Admin界面来接受管理员上传的Excel文件,其中每个Excel文件中的数据都插入到我的数据库模型中。我怎样才能让这样一个“上传”按钮出现在Django模型管理页面上,点击该按钮要求管理员选择一个.xls文件,其数据一旦上传完成就被添加到数据库中?通过django将excel数据导入模型admin

+1

这是一个很好的问题 - 我认识的另一位开发人员以前需要在Django之下工作,而且我自己现在需要在我自己的项目之一中。应该重新打开该问题,以便我们可以分享如何将Excel上载工作到Django Admin Interface。 – 2013-02-22 13:59:00

+0

哦 - 同时,还有一个类似的问题,人们可以参考,但涉及'.csv'文件格式,而不是Excel文件格式:http://stackoverflow.com/questions/3974620/ – 2013-02-22 14:00:50

回答

7

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

在forms.py,一个简单的形式与文件上载字段

class ImportExcelForm(forms.Form): 
    file = forms.FileField(label= "Choose excel to upload")  
在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') 

和所建议的其他后使用xlrd从Excel文件中读取数据。我对这个

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..... 
     ... 

一个单独的文件ExcelParser.py(我可以补充一点,Excel是导入数据的可怕,而且容易出错的方式,我在我的工作做了很多的它,我试图说服管理层有更好的解决方案。)

2

django-import-export可能会有所帮助。

它为admin对象创建两个“导入”和“导出”按钮,并允许选择多种类型的扩展,包括xls。它还显示数据将被导入并要求在执行执行前进行确认。

您只需将其包含在INSTALLED_APPS中,并创建要上载的类的导入导出资源和与之前创建的资源类相关的ImportExportModelAdmin的子类,以在admin中显示按钮。

http://django-import-export.readthedocs.org/en/latest/getting_started.html https://github.com/bmihelac/django-import-export:在

更多信息。