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, joinfrom os import mkdirfrom .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表格显示在网页中了

相关文章