eb84a37b82cafac04df04abf217d6231d296d105
[auf_rh_dae.git] / project / rh / ods.py
1 # encoding: utf-8
2
3 from decimal import Decimal
4
5 import odf.opendocument
6 import odf.style
7 import odf.table
8
9
10 class Wrapper(object):
11
12 def __init__(self, *args, **kwargs):
13 self.__wrapped = self._wrapper_constructor(*args, **kwargs)
14
15 def __getattr__(self, attr):
16 return getattr(self.__wrapped, attr)
17
18
19 class OpenDocumentSpreadsheet(Wrapper):
20 _wrapper_constructor = staticmethod(
21 odf.opendocument.OpenDocumentSpreadsheet
22 )
23
24 def __init__(self, *args, **kwargs):
25 super(OpenDocumentSpreadsheet, self).__init__(*args, **kwargs)
26 self._automatic_style_idx = 0
27
28 def add_table(self, **kwargs):
29 table = Table(**kwargs)
30 table._doc = self
31 self.spreadsheet.addElement(table)
32 return table
33
34 def add_automatic_style(self, **kwargs):
35 name = 'auto_style_%d' % self._automatic_style_idx
36 style = odf.style.Style(name=name, **kwargs)
37 self.automaticstyles.addElement(style)
38 self._automatic_style_idx += 1
39 return style
40
41
42 class Table(Wrapper):
43 _wrapper_constructor = staticmethod(odf.table.Table)
44
45 def add_row(self, values=[], **kwargs):
46 # attributs appartenant à table-column-poperties
47 props = {}
48 for attr in ['rowheight']:
49 if attr in kwargs:
50 props[attr] = kwargs.pop(attr)
51
52 style = self._doc.add_automatic_style()
53 if 'rowheight' in kwargs:
54 style.addElement(odf.style.TableRowProperties(
55 rowheight=kwargs['rowheight']))
56 kwargs['stylename'] = style.getAttribute('name')
57 del kwargs['rowheight']
58
59 if 'verticalalign' in kwargs:
60 style.addElement(odf.style.TableCellProperties(
61 verticalalign=kwargs['verticalalign']))
62 kwargs['stylename'] = style.getAttribute('name')
63 del kwargs['verticalalign']
64
65
66 row = TableRow(**kwargs)
67 for value in values:
68 row.add_cell(value)
69 self.addElement(row)
70 return row
71
72 def add_column(self, **kwargs):
73
74 # attributs appartenant à table-column-poperties
75 props = {}
76 for attr in ['columnwidth']:
77 if attr in kwargs:
78 props[attr] = kwargs.pop(attr)
79
80 if props:
81 style = self._doc.add_automatic_style(family='table-column')
82 style.addElement(odf.style.TableColumnProperties(**props))
83 kwargs['stylename'] = style.getAttribute('name')
84 col = odf.table.TableColumn(**kwargs)
85 self.addElement(col)
86 return col
87
88
89 class TableRow(Wrapper):
90 _wrapper_constructor = staticmethod(odf.table.TableRow)
91
92 def add_cell(self, value=None, **kwargs):
93 if value:
94 if isinstance(value, basestring):
95 kwargs['stringvalue'] = value
96 elif isinstance(value, (int, float, Decimal)):
97 kwargs['valuetype'] = 'float'
98 kwargs['value'] = float(value)
99 cell = odf.table.TableCell(**kwargs)
100 self.addElement(cell)
101 return cell