import pandas as pd | |
from jinja2 import Template | |
# Read the CSV file | |
df = pd.read_csv('sample_data.csv') | |
# Calculate column totals (excluding the first column which contains row labels) | |
totals = df.iloc[:, 1:].sum() | |
# Create HTML template | |
html_template = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>CSV Data Report</title> | |
<style> | |
body { | |
font-family: Arial, sans-serif; | |
margin: 20px; | |
} | |
table { | |
border-collapse: collapse; | |
width: 100%; | |
margin-bottom: 20px; | |
} | |
th, td { | |
border: 1px solid #ddd; | |
padding: 8px; | |
text-align: right; | |
} | |
th { | |
background-color: #f2f2f2; | |
} | |
.total-row { | |
font-weight: bold; | |
background-color: #e6e6e6; | |
} | |
h1 { | |
color: #333; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>CSV Data Report</h1> | |
<h2>Raw Data</h2> | |
{{ raw_data | safe }} | |
<h2>Column Totals</h2> | |
<table> | |
<tr> | |
{% for column in totals.index %} | |
<th>{{ column }}</th> | |
{% endfor %} | |
</tr> | |
<tr class="total-row"> | |
{% for value in totals.values %} | |
<td>{{ "{:,.2f}".format(value) }}</td> | |
{% endfor %} | |
</tr> | |
</table> | |
</body> | |
</html> | |
""" | |
# Convert the raw data to HTML | |
raw_data_html = df.to_html(index=False, classes='table') | |
# Create the template and render it | |
template = Template(html_template) | |
html_output = template.render(raw_data=raw_data_html, totals=totals) | |
# Save the HTML output | |
with open('report.html', 'w') as f: | |
f.write(html_output) | |
print("Report has been generated as 'report.html'") |