rbpu_datasheet/doc_builder/render_table.py

31 lines
854 B
Python
Raw Normal View History

2026-07-19 20:56:15 +08:00
"""Generic CSV table renderer. Used for all CSV @import unless overridden."""
import csv
from html import escape
def render(filepath):
"""Load CSV and render as HTML table."""
rows = []
with open(str(filepath), encoding='utf-8') as f:
for row in csv.DictReader(f):
rows.append({
k.strip(): v.strip() if v else ''
for k, v in row.items()
})
if not rows:
return '<p><em>empty file</em></p>'
cols = list(rows[0].keys())
h = ['<table><thead><tr>']
for c in cols:
h.append(f'<th>{escape(c)}</th>')
h.append('</tr></thead><tbody>')
for r in rows:
h.append('<tr>')
for c in cols:
h.append(f'<td>{escape(str(r.get(c, "")))}</td>')
h.append('</tr>')
h.append('</tbody></table>')
return '\n'.join(h)