Django中如何无需预定义字段将Excel数据渲染为HTML类Excel表格
实现无需预定义字段上传任意Excel并在HTML展示的方案
核心结论
可以实现,无需预先定义和Excel列对应的固定字段,直接通过pyexcel读取文件的动态内容再交给模板渲染即可。
具体实现步骤
第一步:安装必要依赖
执行以下命令安装需要的库:pip install pyexcel pyexcel-xls pyexcel-xlsx django-pyexcel第二步:编写Django视图逻辑
无需定义绑定固定字段的Model,直接在视图中读取上传的Excel文件内容,拆分表头和数据行后传递给模板:
from django.shortcuts import render from django.http import HttpResponseBadRequest import pyexcel def excel_upload_view(request): if request.method == "POST" and request.FILES.get("excel_file"): uploaded_file = request.FILES["excel_file"] # 校验文件格式合法性 allowed_suffix = ["xls", "xlsx"] file_suffix = uploaded_file.name.split(".")[-1].lower() if file_suffix not in allowed_suffix: return HttpResponseBadRequest("仅支持上传xls、xlsx格式的Excel文件") # 直接读取Excel全部内容,无需匹配预定义字段 sheet = pyexcel.get_sheet( file_type=file_suffix, file_content=uploaded_file.read() ) if sheet.number_of_rows() == 0: return HttpResponseBadRequest("上传的Excel文件无有效数据") # 拆分表头和数据行 headers = sheet.row[0] data_rows = sheet.row[1:] return render(request, "excel_display.html", { "headers": headers, "data_rows": data_rows }) # GET请求返回上传页面 return render(request, "upload.html")
- 第三步:编写上传页面模板(upload.html)
<form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="excel_file" accept=".xls,.xlsx" required> <button type="submit">上传并展示</button> </form>
- 第四步:编写Excel内容展示模板(excel_display.html)
不需要写死列名,动态遍历表头和行数据即可适配任意结构的Excel:
<table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> {% for header in headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in data_rows %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
注意事项
- 可以根据业务需求增加文件大小限制,避免大文件占用过多内存
- 如果存在多sheet的Excel,可以调整逻辑遍历所有sheet的内容分别展示
- 遇到空单元格等异常情况,可以额外加判断处理默认展示值
内容的提问来源于stack exchange,提问作者project.py
相关产品推荐
相关产品推荐

