0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csv to html.table using jinja2 memo

Last updated at Posted at 2017-12-07

メモ

  • 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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?