2012-04-02 99 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:在

更多信息。