前言
最近在做基於機器學習的預測系統,里面需要用到excel表格的上傳和顯示,在這把過程記錄一下
Excel文件的上傳
-
在頁面中加入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> -
修改應用文件夾中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}) -
修改應用文件夾中的urls.py文件
urlpatterns = [ path('index/', views.upload,), path('admin/', admin.site.urls), ]
Excel文件的讀取與顯示
- 首先在views.py文件中添加需要用到的庫
接着修改剛才的上傳函數import pandas as pddef 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}) - 最后在頁面中增加
{% autoescape off %} {{form}} {% endautoescape %} - 執行命令,運行服務器,即可上傳文件並且將上傳的Excel表格顯示在網頁中了
