1 # -*- coding: utf-8 -*-
4 from StringIO
import StringIO
5 from odf
.opendocument
import OpenDocumentSpreadsheet
6 from odf
.style
import Style
, TextProperties
, TableColumnProperties
8 from odf
.table
import Table
, TableRow
, TableCell
10 from django
.http
import HttpResponse
11 from django
.utils
.datastructures
import SortedDict
13 __all__
= ("formats", )
16 class FormatsException(Exception):
20 class Formats(SortedDict
):
22 def add(self
, format
):
27 parent
.update({format
: func
})
29 raise FormatsException("func is not a function.")
37 # Taken from http://docs.python.org/library/csv.html#csv-examples
38 class UnicodeWriter(object):
40 A CSV writer which will write rows to CSV file "f",
41 which is encoded in the given encoding.
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
)
49 self
.encoder
= codecs
.getincrementalencoder(encoding
)()
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
)
61 self
.queue
.truncate(0)
63 def writerows(self
, rows
):
70 if msg
is not None and not isinstance(msg
, unicode):
71 text
= unicode (msg
, "utf-8")
75 def base_export(labels
, results
, dialect
=csv
.excel_tab
):
77 w
= UnicodeWriter(output
, dialect
=dialect
)
86 def csv_format(labels
, results
):
87 output
= base_export(labels
, results
, dialect
=csv
.excel
)
89 response
= HttpResponse(output
, mimetype
=mimetype
)
90 response
['Content-Disposition'] = 'attachment; filename=export.csv'
95 def 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
)
107 table
.addElement (tr
)
111 p
= P(stylename
= style
, text
= txt(item
))
116 table
.addElement (tr
)
120 p
= P (stylename
= style
, text
= txt(item
))
123 doc
.spreadsheet
.addElement(table
)
127 mimetype
= "application/vnd.oasis.opendocument.spreadsheet"
128 response
= HttpResponse(buffer.getvalue(), mimetype
=mimetype
)
129 response
['Content-Disposition'] = 'attachment; filename=export.ods'
134 def 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'