πŸ› οΈToolsShed

CSV to HTML Table Generator

Convert CSV data to an HTML table with live preview. Options for styling, headers, and CSS classes.

Frequently Asked Questions

Code Implementation

import csv
import io

def csv_to_html_table(csv_text, has_header=True, bordered=True):
    reader = csv.reader(io.StringIO(csv_text.strip()))
    rows = list(reader)
    if not rows:
        return ""

    style = ""
    if bordered:
        style = "<style>table{border-collapse:collapse}th,td{border:1px solid #ddd;padding:8px}th{background:#4f46e5;color:#fff}</style>\n"

    html = [style + '<table class="table">']
    start = 0
    if has_header:
        html.append("  <thead><tr>")
        for cell in rows[0]:
            html.append(f"    <th>{cell}</th>")
        html.append("  </tr></thead>")
        start = 1

    html.append("  <tbody>")
    for row in rows[start:]:
        html.append("  <tr>")
        for cell in row:
            html.append(f"    <td>{cell}</td>")
        html.append("  </tr>")
    html.append("  </tbody>")
    html.append("</table>")
    return "\n".join(html)

csv_data = """Name,Age,City
Alice,30,New York
Bob,25,London
Carol,35,Tokyo"""

print(csv_to_html_table(csv_data))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.