Django文件的上傳和數據顯示


前言

最近在做基於機器學習的預測系統,里面需要用到excel表格的上傳和顯示,在這把過程記錄一下

Excel文件的上傳

  1. 在頁面中加入form表單

    <form method="POST" action="/index/" enctype="multipart/form-data">
      {% csrf_token %}
        <input class="form-control-file" type="file" name="Scores" accept=".xlsx, .xls"/>
        <input class="form-control-file" type="submit" value="上傳"/>
        {% if msg %}
          <span>
            {{msg}}
          </span>
        {% endif %}
    </form>
    
  2. 修改應用文件夾中views.py文件

    首先導入用到的庫

    from os.path import isdir, dirname, join
    from os import mkdir
    from .settings import BASE_DIR
    

    接着增加上傳函數

    def upload(request):
        if request.method == 'POST':
            # 創建用來存儲上傳文件的文件夾
            uploadDir = BASE_DIR+'/upload'
            if not isdir(uploadDir):
                mkdir(uploadDir)
            # 獲取上傳的文件
            uploadedFile = request.FILES.get('Scores')
            if not uploadedFile:
                return render(request, 'index.html', {'msg':'沒有選擇文件'})
            if not uploadedFile.name.endswith('.xlsx'):
                if not uploadedFile.name.endswith('.xls'):
                    return render(request, 'index.html', {'msg':'必須選擇xlsx或xls文件'})
            # 上傳
            dstFilename = join(uploadDir, uploadedFile.name)
            with open(dstFilename, 'wb') as fp:
                for chunk in uploadedFile.chunks():
                    fp.write(chunk)
            context = {}
            context['msg'] = '上傳成功'
            return render(request, 'index.html', context)
        else:
            return render(request, 'index.html',{'msg':None})
    
  3. 修改應用文件夾中的urls.py文件

    urlpatterns = [
     path('index/', views.upload,),
     path('admin/', admin.site.urls),
    ]
    

Excel文件的讀取與顯示

  1. 首先在views.py文件中添加需要用到的庫
    import pandas as pd
    
    接着修改剛才的上傳函數
    def upload(request):
     if request.method == 'POST':
         # 創建用來存儲上傳文件的文件夾
         uploadDir = BASE_DIR+'/upload'
         if not isdir(uploadDir):
             mkdir(uploadDir)
         # 獲取上傳的文件
         uploadedFile = request.FILES.get('Scores')
         if not uploadedFile:
             return render(request, 'index.html', {'msg':'沒有選擇文件'})
         if not uploadedFile.name.endswith('.xlsx'):
             if not uploadedFile.name.endswith('.xls'):
                 return render(request, 'index.html', {'msg':'必須選擇xlsx或xls文件'})
         # 上傳
         dstFilename = join(uploadDir, uploadedFile.name)
         with open(dstFilename, 'wb') as fp:
             for chunk in uploadedFile.chunks():
                 fp.write(chunk)
         # 讀取excel文件並轉化為html格式
         pdData = pd.read_excel(dstFilename)
         pdhtml = pdData.to_html()
         context = {}
         context['form'] = pdhtml
         context['msg'] = '上傳成功'
         return render(request, 'index.html', context)
     else:
         return render(request, 'index.html',{'msg':None})
    
  2. 最后在頁面中增加
     {% autoescape off %}
        {{form}}
     {% endautoescape %}
    
  3. 執行命令,運行服務器,即可上傳文件並且將上傳的Excel表格顯示在網頁中了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM