-
Notifications
You must be signed in to change notification settings - Fork 3
/
csv2html.py
80 lines (52 loc) · 1.62 KB
/
csv2html.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python2
""" Very simplistic csv to html table converter """
__authors__ = ['haxwithaxe <[email protected]>']
__license__ = 'GPLv3'
import csv
def attrib_to_string(**attribs):
if not attribs:
return ''
return ' '.join(['%s="%s"' % (key,value) for key,value in attribs])
def xml_elem(*strings, **attribs):
return '<%s %s>%s</%s>' % (elem, attrib_to_string(**attribs) , ''.join(strings), elem)
def td(*strings, **attribs):
attribs['elem'] = 'td'
return xml_elem(*strings, **attribs)
def th(*strings, **attribs):
attribs['elem'] = 'th'
return xml_elem(*strings, **attribs)
def tr(*strings, **attribs):
attribs['elem'] = 'tr'
return xml_elem(*strings, **attribs)
def table(*string, **attribs):
attribs['elem'] = 'table'
return xml_elem(*string, **attribs)
def load_csv(filename):
with open(filename, 'rb') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
def make_header(reader):
headers = []
for f in reader.fieldnames:
headers.append(th(f))
return tr(*headers)
def make_contents(reader):
body = []
line = True
while line:
row = []
line = reader.next()
if line:
for i in line:
row.append(td(i))
body.append(tr(row))
return body
def make_table(reader):
header = make_header(reader)
body = make_contents(reader)
header += body
return table(header*)
def make_page(reader):
t = make_table(reader)
return xml_elem(xml_elem(t, elem='body'), 'html')