You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask的home.html模板中嵌入并格式化Pandas DataFrame?

解决Flask中Pandas DataFrame无法嵌入模板的问题

嘿,我懂你踩的这个坑!之前我也犯过一模一样的错——直接返回df.to_html()的结果,结果Flask直接把表格当成整个页面返回,完全忽略了我们精心写的模板。别慌,咱们一步步把它搞定:

第一步:修改你的Flask视图函数

你需要把DataFrame转成HTML字符串,然后把这个字符串作为参数传给模板,而不是直接返回它。示例代码如下:

from flask import Flask, render_template
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    # 读取CSV并筛选目标列
    df_holdings = pd.read_csv('Holdings.csv')
    df_holdings = df_holdings[['Sector','Security','Position']]  # 补全你需要的列
    
    # 把DataFrame转成HTML字符串,可加classes参数给表格预设样式(比如Bootstrap类)
    table_html = df_holdings.to_html(classes='table table-striped', index=False)
    
    # 将表格HTML作为变量传给home.html模板
    return render_template('home.html', holdings_table=table_html)

这里的核心是:用render_template返回模板,同时把表格HTML作为变量传入,而不是直接返回table_html。

第二步:在home.html模板中嵌入表格

现在需要在模板的合适位置渲染这个表格变量,注意要加|safe过滤器——因为Jinja2默认会转义HTML字符,不加的话你会看到一堆<table>这样的代码,而不是实际的表格。

示例模板代码:

<!DOCTYPE html>
<html>
<head>
    <title>我的持仓页面</title>
    <!-- 可选:引入Bootstrap CSS让表格更美观 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1>欢迎查看我的持仓</h1>
        <!-- 嵌入表格的位置 -->
        {{ holdings_table|safe }}
    </div>
</body>
</html>

额外优化:自定义表格样式

如果不想用Bootstrap,也可以自己写CSS美化表格,比如在模板的<head>里添加:

<style>
    .custom-table {
        width: 90%;
        margin: 20px auto;
        border-collapse: collapse;
        font-family: Arial, sans-serif;
    }
    .custom-table th {
        background-color: #4CAF50;
        color: white;
        padding: 12px;
        text-align: left;
    }
    .custom-table td {
        padding: 10px;
        border-bottom: 1px solid #ddd;
    }
    .custom-table tr:hover {
        background-color: #f5f5f5;
    }
</style>

然后转HTML时指定自定义类:df_holdings.to_html(classes='custom-table', index=False)即可。

为什么之前的方法不行?

你之前应该是直接return df_holdings.to_html()了,这相当于告诉Flask:“整个HTTP响应就是这个表格的HTML”,所以它完全不会去加载你的home.html模板。只有用render_template把模板和变量结合,才能让表格嵌入到你想要的位置。

内容的提问来源于stack exchange,提问作者dz333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:28:48