Python
jinja2
pandas

csv to html.table using jinja2 memo

メモ

  • DB -> pandas ---export---> csv ---import---> df ---> list() -> jinja2

  • hoge.csv

import pandas as pd
df = pd.DataFrame({'name': ['apple', 'orange'], 'price': ['$1', '$2']})
df.to_csv('hoge.csv', index=None)
  • app.py
# -*- coding: utf-8 -*-

import pandas as pd
from flask import Flask, render_template

# make instance
app = Flask(__name__)

# show csv data as table format
@app.route("/csvtbl")
def csvtbl():
    # import csv as pandas.Dataframe
    df = pd.read_csv('hoge.csv')
    return render_template('csvtbl.html',
                           title='CSV to table',
                           # df to list format
                           data = list(df.values.flatten()))

if __name__ == "__main__":
    app.run(debug=True)
  • csvtbl.html
<table>
    <thead>
        <tr>
        {# get column name #}
        {% for key, item in data.items() %}
            <th>{{key}}</th>
        {% endfor %}
        </tr>
    </thead>
    <tbody>
    <tr>
        {# set value#}
        {% for row in data2 %}
            <td>{{row}}</td>
        {# if show 3 columns, show next row #}
        {% if loop.index0 % 2 == 1 %}
    </tr>
    <tr>
        {% endif %}
        {% endfor %}
    </tr>
    </tbody>
</table>
  • localhost:5000/csvtbl.html

tbl.png