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