Routeur: Ajout temporaire des modules workflow et dae en écriture
[auf_rh_dae.git] / src / qbe / django_qbe / exports.py
CommitLineData
5cf90361
PP
1# -*- coding: utf-8 -*-
2import codecs
3import csv
4from StringIO import StringIO
5from odf.opendocument import OpenDocumentSpreadsheet
6from odf.style import Style, TextProperties, TableColumnProperties
7from odf.text import P
8from odf.table import Table, TableRow, TableCell
9
10from django.http import HttpResponse
11from django.utils.datastructures import SortedDict
12
13__all__ = ("formats", )
14
15
16class FormatsException(Exception):
17 pass
18
19
20class Formats(SortedDict):
21
22 def add(self, format):
23 parent = self
24
25 def decorator(func):
26 if callable(func):
27 parent.update({format: func})
28 else:
29 raise FormatsException("func is not a function.")
30
31 return decorator
32
33
34formats = Formats()
35
36
37# Taken from http://docs.python.org/library/csv.html#csv-examples
38class UnicodeWriter(object):
39 """
40 A CSV writer which will write rows to CSV file "f",
41 which is encoded in the given encoding.
42 """
43
44 def __init__(self, f, dialect=csv.excel_tab, encoding="utf-8", **kwds):
45 # Redirect output to a queue
46 self.queue = StringIO()
47 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
48 self.stream = f
49 self.encoder = codecs.getincrementalencoder(encoding)()
50
51 def writerow(self, row):
52 self.writer.writerow([unicode(s).encode("utf-8") for s in row])
53 # Fetch UTF-8 output from the queue ...
54 data = self.queue.getvalue()
55 data = data.decode("utf-8")
56 # ... and reencode it into the target encoding
57 data = self.encoder.encode(data)
58 # write to the target stream
59 self.stream.write(data)
60 # empty queue
61 self.queue.truncate(0)
62
63 def writerows(self, rows):
64 for row in rows:
65 self.writerow(row)
66
67
68def txt(msg):
69 text = msg
65f85549 70 if msg is not None and isinstance(msg, str):
5cf90361
PP
71 text = unicode (msg, "utf-8")
72 return text
73
74
75def base_export(labels, results, dialect=csv.excel_tab):
76 output = StringIO()
77 w = UnicodeWriter(output, dialect=dialect)
78 w.writerow(labels)
79 for row in results:
80 w.writerow(row)
81 output.seek(0)
82 return output.read()
83
84
85@formats.add("csv")
86def csv_format(labels, results):
87 output = base_export(labels, results, dialect=csv.excel)
88 mimetype = "text/csv"
89 response = HttpResponse(output, mimetype=mimetype)
90 response['Content-Disposition'] = 'attachment; filename=export.csv'
91 return response
92
93
94@formats.add("ods")
95def ods_format(labels, results):
96 doc = OpenDocumentSpreadsheet()
97 style = Style(name="Large number", family="table-cell")
98 style.addElement(TextProperties(fontfamily="Arial", fontsize="15pt"))
99 doc.styles.addElement(style)
100 widewidth = Style(name="co1", family="table-column")
101 widewidth.addElement(TableColumnProperties(columnwidth="2.8cm", breakbefore="auto"))
102 doc.automaticstyles.addElement(widewidth)
103
104 table = Table()
105 if len (labels) > 0:
106 tr = TableRow ()
107 table.addElement (tr)
108 for item in labels:
109 tc = TableCell ()
110 tr.addElement (tc)
111 p = P(stylename = style, text = txt(item))
112 tc.addElement (p)
113
114 for line in results:
115 tr = TableRow ()
116 table.addElement (tr)
117 for item in line:
118 tc = TableCell ()
119 tr.addElement (tc)
120 p = P (stylename = style, text = txt(item))
121 tc.addElement (p)
122
123 doc.spreadsheet.addElement(table)
124 buffer = StringIO ()
125 doc.write(buffer)
126
127 mimetype = "application/vnd.oasis.opendocument.spreadsheet"
128 response = HttpResponse(buffer.getvalue(), mimetype=mimetype)
129 response['Content-Disposition'] = 'attachment; filename=export.ods'
130 return response
131
132
133@formats.add("xls")
134def xls_format(labels, results):
135 output = base_export(labels, results)
136 mimetype = "application/vnd.ms-excel"
137 response = HttpResponse(output, mimetype=mimetype)
138 response['Content-Disposition'] = 'attachment; filename=export.xls'
139 return response