CSV to HTML
Python
Publicado el 10 de Diciembre del 2017 por D4redevilx (4 códigos)
2.039 visualizaciones desde el 10 de Diciembre del 2017
Convierte un fichero CSV a una tabla html.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
from string import Template
html_template = Template("""
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>$title</title>
<style>
* {margin: 0; padding: 0; font-size: 16px; box-sizing: border-box;}
body {font-family: Helvetica, sans-serif; color: #212121}
table {border-collapse: collapse; width: 100%;}
table, td {border: 1px solid #acacac;}
td { padding: .3rem;}
.datasheet {max-width: 960px; width: 100%; margin: 1rem auto;
overflow: auto;}
</style>
</head>
<body>
<div class="datasheet">
<table>$content</table>
</div>
</body>
</html>""")
def csv_to_html(csv_file, dest_filename='index.html', title='Document'):
""" Convierte un archivo csv a una tabla en formato html. """
with open(csv_file, mode='r') as f:
# detecto el dialecto utilizado por el archivo
dialect = csv.Sniffer().sniff(f.read(1024))
f.seek(0)
csv_reader = csv.reader(f, dialect)
rows = ''
for line in csv_reader:
cols = ''
for field in line:
cols += '<td>{}</td>'.format(field)
rows += '<tr>{}</tr>'.format(cols)
# creo el archivo html
with open(dest_filename, mode='w') as f:
content = html_template.substitute(title=title, content=rows)
f.write(content)
Comentarios sobre la versión: 1.0.0 (2)