如何在Django的HTML模板中展示openpyxl读取的Excel数据
实现步骤
1. 视图层整理openpyxl读取的数据
首先你需要把openpyxl读取到的工作表对象,整理成模板可以直接渲染的结构化数据(推荐嵌套列表或者列表套字典两种格式),示例代码如下:
# views.py from django.shortcuts import render from openpyxl import load_workbook def render_excel(request): # 加载Excel文件,支持本地文件或用户上传的文件对象 wb = load_workbook("test.xlsx", read_only=True) ws = wb.active # 取激活的工作表,也可通过wb["工作表名称"]指定 # 方案1:整理为嵌套列表(无需自定义过滤器,适配简单场景) excel_list = [] for row in ws.iter_rows(values_only=True): excel_list.append([cell for cell in row]) # 方案2:整理为列表套字典(方便按字段单独处理内容) # headers = [cell.value for cell in next(ws.iter_rows(min_row=1, max_row=1))] # excel_list = [dict(zip(headers, row)) for row in ws.iter_rows(min_row=2, values_only=True)] # 将数据传入模板上下文 return render(request, "excel_page.html", {"excel_data": excel_list})
2. 配置路由
在app的urls.py中添加路由映射:
from django.urls import path from . import views urlpatterns = [ path("excel/", views.render_excel, name="show_excel"), ]
3. 模板层渲染数据
如果用上面的方案1(嵌套列表),直接循环渲染即可,无需额外处理:
<!-- templates/excel_page.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Excel数据展示</title> <style> table{width: 95%;margin: 20px auto;border-collapse: collapse;} th,td{border:1px solid #eee;padding:8px 12px;} th{background: #f5f5f5;} </style> </head> <body> <h2 style="text-align:center">Excel数据列表</h2> <table> {% for row in excel_data %} <tr> {% for cell in row %} <!-- 第一行自动作为表头 --> {% if forloop.parentloop.first %} <th>{{ cell }}</th> {% else %} <td>{{ cell }}</td> {% endif %} {% endfor %} </tr> {% empty %} <tr> <td style="text-align:center">未读取到有效数据</td> </tr> {% endfor %} </table> </body> </html>
如果你选择了方案2(列表套字典),需要先自定义一个模板过滤器实现字典取值:
- 在app目录下新建
templatetags文件夹,新增custom_filters.py文件:
from django import template register = template.Library() @register.filter def get_value(dic, key): return dic.get(key)
- 在模板顶部引入过滤器:
{% load custom_filters %},然后循环时取值写法为{{ row|get_value:header }}即可。
内容的提问来源于stack exchange,提问作者Prateek p
相关产品推荐
相关产品推荐

