如何使用 Flask 和 JSON 变量通过 Tabulator 显示 table

How to show a table with Tabulator using Flask and a JSON variable

我刚开始使用 Flask 和 JQuery,我需要一些帮助。 我想显示一个 table (我想稍后变成动态的),但我找不到如何 link 我输入参数的 table (JSON)在 render_template 和 table 中,我想使用 Tabulator 在我的 html 页面上显示。

这是我的 app.py :

import os
from flask import Flask, render_template
import pandas as pd
import excel2json

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'upload_folder'

df = pd.read_excel(os.path.join(app.config['UPLOAD_FOLDER'], "file.xlsx"), engine="openpyxl")
df = df.to_json()

@app.route('/')
def index():
   return render_template('index.html', tables=df)

这就像我想要的那样工作(我将 df 转换为 Json 以备后用,这不是我的问题)

<html>
  <head>
    <script src='static/jquery.js'></script>
    <script src='static/jquery-ui.js'></script>
    <link rel='stylesheet' href='static/tabulator.css'>
    <script src='static/tabulator.js'></script>
  </head>

  <body>

  <div id='example-table'>
    <script type='text/javascript'>

      var table = new Tabulator(#example-table, {
      columns:[
      {title:"col1", field="col1"},
      {title:"col2", field="col2"},
      {title:"col3", field="col3"}
      ]
      });

      var tabledata = tables.getData();

    </script>
  </body>

当我使用时:

var tabledata = [
{col1:0, col2:3, col3:6},
{col1:1, col2:4, col3:7},
{col1:2, col2:5, col3:8}
]

有效

但显然,我的最后一部分不起作用。我的问题是:如何将参数 tables (app.py) 放入 tabledata ?

tables的格式是:tables= {"col1":{0,1,2}, "col2":{3,4,5}, "col3":{6,7,8}}

感谢您的帮助:)

您可以将加载的数据作为 dict 传递给具有特定方向的模板。

@app.route('/')
def index():
   src = os.path.join(app.config['UPLOAD_FOLDER'], 'file.xlsx')
   df = pd.read_excel(src, engine='openpyxl')
   return render_template('index.html', data=df.to_dict(orient='records')

然后在 jinja2 过滤器 tojson 的帮助下将数据转换为 javascript 兼容变体 tojson

<html>
  <head>
    <link href="https://unpkg.com/tabulator-tables@4.1.4/dist/css/tabulator.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.1.4/dist/js/tabulator.min.js"></script>
  </head>
  <body>
    <div id="example-table"></div>
    <script type="text/javascript">
      const tabledata = {{ data | tojson }};
      const table = new Tabulator(
        "#example-table",
        {
          data:tabledata,
          columns:[
            {title:"col1", field:"col1"},
            {title:"col2", field:"col2"},
            {title:"col3", field:"col3"}
          ]
        }
      );
    </script>
  </body>
</html>

只要定义的列与数据中的信息匹配,table 就会按需要显示。