【问题标题】:Import excel data into models via django admin通过 django admin 将 excel 数据导入模型
【发布时间】:2012-04-16 12:01:53
【问题描述】:

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

【问题讨论】:

  • 这是一个很好的问题——我认识的另一位开发人员以前在 Django 下需要它,而我自己现在在我自己的一个项目中也需要它。这个问题应该重新打开,以便我们可以分享我们如何让 Excel 上传到 Django 管理界面。
  • 哦——同时,人们可以咨询一个类似的问题,但这涉及.csv文件格式而不是Excel文件格式:stackoverflow.com/questions/3974620

标签: python django django-admin xls


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我已经这样做了,但我只是设置了一个带有文件上传的简单视图(实际上这比直接将其添加到 Django 管理页面更有意义,因为一个编辑页面 = 一个模型实例,我假设您的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 文件中读取数据。我为此有一个单独的文件 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.....
            ...
    

    (我可以补充一点,Excel 是一种糟糕且容易出错的数据导入方式。我在工作中做了很多工作,并试图让管理层相信有更好的解决方案。)

    【讨论】:

      【解决方案3】:

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

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

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

      更多信息请访问:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-04
        • 2016-10-27
        • 1970-01-01
        • 2021-02-10
        • 2011-04-27
        • 2014-08-30
        • 2018-09-26
        • 2018-05-03
        相关资源
        最近更新 更多