Correction #336
[django-exportateur.git] / django_exportateur / exportateur.py
CommitLineData
fd47c85b
CR
1from django.http import HttpResponse
2import csv
3from StringIO import StringIO
4from odf.opendocument import OpenDocumentSpreadsheet
5from odf.style import Style, TextProperties, TableColumnProperties
6from odf.text import P
7from odf.table import Table, TableRow, TableCell
8
9mimetypes = {"csv": "text/csv", \
10 "ods": "application/vnd.oasis.opendocument.spreadsheet"}
11
12def export_csv (headers, data):
13 buffer = StringIO ()
14 writer = csv.writer (buffer)
15 if len (headers) > 0:
16 writer.writerow (headers)
17 for line in data:
18 writer.writerow (line)
19
20 return buffer.getvalue ()
21
91782a7d
CR
22def txt(msg):
23 text = msg
24 if not isinstance(msg, unicode):
25 text = unicode (msg, "utf-8")
26 return text
27
fd47c85b
CR
28def export_ods (headers, data):
29 doc = OpenDocumentSpreadsheet()
30 style = Style(name="Large number", family="table-cell")
31 style.addElement(TextProperties(fontfamily="Arial", fontsize="15pt"))
32 doc.styles.addElement(style)
33 widewidth = Style(name="co1", family="table-column")
34 widewidth.addElement(TableColumnProperties(columnwidth="2.8cm", breakbefore="auto"))
35 doc.automaticstyles.addElement(widewidth)
36
37 table = Table()
38 if len (headers) > 0:
39 tr = TableRow ()
40 table.addElement (tr)
41 for item in headers:
42 tc = TableCell ()
43 tr.addElement (tc)
91782a7d 44 p = P(stylename = style, text = txt(item))
fd47c85b
CR
45 tc.addElement (p)
46
47 for line in data:
48 tr = TableRow ()
49 table.addElement (tr)
50 for item in line:
51 tc = TableCell ()
52 tr.addElement (tc)
91782a7d 53 p = P (stylename = style, text = txt(item))
fd47c85b
CR
54 tc.addElement (p)
55
56 doc.spreadsheet.addElement(table)
57 buffer = StringIO ()
58 doc.write(buffer)
59
60 return buffer.getvalue ()
61
62
63def exportateur (headers = [], data = [], type = "csv", filename = None):
64 content = None
65 if type == "csv":
66 content = export_csv (headers, data)
67 elif type == "ods":
68 content = export_ods (headers, data)
69 else:
70 raise "Type d'exportateur inconnu: %s" % type
71
72 if filename is None:
73 filename = "exportateur.%s" % type
74
75 response = HttpResponse (mimetype = mimetypes[type])
76 response['Content-Disposition'] = "attachment; filename=\"%s\"" % filename
77 response.write (content)
78
79 return response