Python convert CSV to HTML Table
This tutorial is Python convert CSV to HTML Table
. I would perform this task using the Pandas library. you would have to do to get the data into table format is. CSV file is a Comma Separated Value file that uses a comma to separate values.
One of the easiest ways to convert CSV files to HTML tables is by using pandas. pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool. Type the below code in the command prompt to install pandas.
Using pandas
$ pip install pandas
Example
import pandas as pd
csv_file = pd.read_csv("csv_file.csv")
csv_file.to_html("html_table.html")
html_file = csv_file.to_html()
Output
Using for loop
When you find a row you want to print, output it in HTML table row format.
Example
import csv
table = ""
tr = ""
file_name = "csv_data.csv"
with open(file_name) as file:
table += "<table border=1 cellpadding=1><tr><th>Name</th><th>Salary</th><th>Age</th></tr>"
csv_reader_object = csv.reader(file)
next(csv_reader_object)
for line in csv_reader_object:
name = line[0]
salary = line [1]
age = line[2]
tr += "<tr>"
tr += "<td>%s</td>" % name
tr += "<td>%s</td>" % salary
tr += "<td>%s</td>" % age
tr += "</tr>"
end = "</table>"
html = table + tr + end
files = open("output.html", "w+")
files.write(html)
files.close()
Output
Vertical HTML Table
import csv
# CSV data
data = [
["name", "raj"],
["salary", "1000"],
["age", "22"]
]
# Start the HTML table
html_table = '<table border="1">\n'
# Add headers for the table (the first row)
html_table += '<tr><th>Attribute</th><th>Value</th></tr>\n'
# Add rows for each entry in the CSV data
for row in data:
html_table += f'<tr><td>{row[0]}</td><td>{row[1]}</td></tr>\n'
# End the HTML table
html_table += '</table>'
# Print the resulting HTML table
print(html_table)
Output
Attribute | Value |
---|---|
name | raj |
salary | 1000 |
age | 22 |
How can I display the table vertically?
name, raj
salary, 1000
age, 22