Convert CSV to HTML Table using Python Pandas and Flask Framework
Last Updated :
26 May, 2022
Improve
In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework.
Sample CSV file :
USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME booker12,9012,Rachel,Booker grey07,2070,Laura,Grey johnson81,4081,Craig,Johnson jenkins46,9346,Mary,Jenkins smith79,5079,Jamie,Smith
Stepwise Implementation
Creating Environment
Step 1: Create an environment. Create a project folder and a venv folder within.
py -3 -m venv venv
Step 2: Activate the environment.
venv\Scripts\activate
Step 3: Install Flask and Pandas.
pip install Flask
pip install pandas
Creating Project
Step 1: Create ‘app.py’ folder and write the code given below.
# importing flask
from flask import Flask, render_template
# importing pandas module
import pandas as pd
app = Flask(__name__)
# reading the data in the csv file
df = pd.read_csv('sample_data.csv')
df.to_csv('sample_data.csv', index=None)
# route to html page - "table"
@app.route('/')
@app.route('/table')
def table():
# converting csv to html
data = pd.read_csv('sample_data.csv')
return render_template('table.html', tables=[data.to_html()], titles=[''])
if __name__ == "__main__":
app.run(host="localhost", port=int("5000"))
Step 2: Create the folder ‘templates’. create the file ‘table.html’ inside the ‘templates’ folder.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Table </title>
</head>
<body>
<div align="center">
<table>
<h1>
<!--Displaying the converted table-->
{% for table in tables %}
<h2>{{titles[loop.index]}}</h2>
{{ table|safe }}
{% endfor %}
</h1>
</table>
</div>
</body>
</html>
Step 3: Add the 'sample_data.csv' file.
Step 4: The project structure will look like this.

Run the Project
Step 1: Run the server.
Step 2: Browse the URL ‘localhost:5000’.
Step 3: The output web page will be displayed.
Output:
