如何在网页中以表格形式展示Excel DataFrame数据
网页仪表盘Excel数据表格展示问题解决
问题背景
我正在开发一款网页版仪表盘,采用Python(Flask)作为后端技术、AngularJS作为前端技术。作为新手,我的首个任务是在网页中以表格形式展示Excel数据。我编写了Python代码读取Excel数据并转换为JSON格式传给前端HTML,但实际输出为JSON格式文本,而非预期的表格形式。
现有代码
后端代码(app.py)
# app.py from flask import Flask, jsonify import pandas as pd app = Flask(__name__) @app.route('/data') def get_data(): # 读取Excel文件到Pandas DataFrame df = pd.read_excel('example.xlsx') # 转换为JSON格式返回 return jsonify(df.to_dict(orient='records')) if __name__ == '__main__': # 启动Flask服务 app.run(debug=True)
前端代码(index.html)
<!-- index.html --> <!DOCTYPE html> <html ng-app="myApp"> <head> <title>My Dashboard</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-controller="ExampleCtrl"> <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody> <tr ng-repeat="row in data"> <td>{{row['Column 1']}}</td> <td>{{row['Column 2']}}</td> <td>{{row['Column 3']}}</td> </tr> </tbody> </table> <script> var app = angular.module('myApp', []); app.controller('ExampleCtrl', function($scope, $http) { $http.get('/data').then(function(response) { $scope.data = response.data; }); }); </script> </body> </html>
预期与实际输出
预期输出
| Column 1 | Column 2 | Column 3 |
|---|---|---|
| 0.23 | 0.44 | 0.54 |
| 0.55 | 0.4 | 0.05 |
实际输出
[ { "Column 1": 0.23, "Column 2": 0.44, "Column 3": 0.54 }, { "Column 1": 0.55, "Column 2": 0.4, "Column 3": 0.05 } ]
问题原因及解决方法
核心问题
你直接访问了/data路由,而Flask当前只配置了这个接口返回JSON数据,没有设置返回前端页面的路由。AngularJS的页面从未被加载,自然无法渲染表格。
修复步骤
修改后端代码,添加根路由
在app.py中导入render_template,并新增根路由返回前端页面:# app.py from flask import Flask, jsonify, render_template # 新增render_template import pandas as pd app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') # 返回前端页面 @app.route('/data') def get_data(): df = pd.read_excel('example.xlsx') return jsonify(df.to_dict(orient='records')) if __name__ == '__main__': app.run(debug=True)调整项目文件结构
Flask默认从templates目录读取模板文件,所以需要创建该目录并将index.html放入其中:你的项目目录/ ├── app.py ├── example.xlsx └── templates/ └── index.html访问正确的路由
启动Flask服务后,访问http://localhost:5000(根路由),而非/data。此时AngularJS会自动请求/data接口获取数据,并将其渲染为表格。
额外检查项
- 确认Excel文件的列名与前端代码中
row['Column 1']的名称完全一致(包括大小写、空格) - 确保AngularJS的CDN链接可正常加载,避免前端渲染逻辑无法执行
内容的提问来源于stack exchange,提问作者Harsh Solanki
相关产品推荐
相关产品推荐

