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

2024-05-19 01:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件数据django模型数据库界面管理员页面
3条回答

django的进出口可能会有帮助。

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

您只需将其包含在已安装的应用程序中,并创建要上载的类的导入导出资源以及与之前创建的资源类相关的ImportExportModelAdmin的子类,即可在admin中显示按钮。

更多信息请访问:

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

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

我已经完成了这项工作,但我只是通过文件上传设置了一个简单的视图(实际上,这比直接将其添加到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是一种糟糕的、容易出错的数据导入方式。我在工作中做了很多工作,并试图让管理层相信有更好的解决方案。)

相关问题 更多 >

    热门问题