-
Notifications
You must be signed in to change notification settings - Fork 8
/
pyoo.py
1968 lines (1605 loc) · 62.3 KB
/
pyoo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PyOO - Pythonic interface to Apache OpenOffice API (UNO)
Copyright (c) 2016-2017 Seznam.cz, a.s.
Copyright (c) 2017-2019 Miloslav Pojman
"""
from __future__ import division
import datetime
import functools
import itertools
import numbers
import os
import sys
import uno
# Filters used when saving document.
FILTER_PDF_EXPORT = 'writer_pdf_Export'
FILTER_WRITER_PDF_EXPORT = 'writer_pdf_Export'
FILTER_CALC_PDF_EXPORT = 'calc_pdf_Export'
FILTER_EXCEL_97 = 'MS Excel 97'
FILTER_EXCEL_2007 = 'Calc MS Excel 2007 XML'
# Number format choices
FORMAT_TEXT = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.TEXT')
FORMAT_INT = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.NUMBER_INT')
FORMAT_FLOAT = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.NUMBER_DEC2')
FORMAT_INT_SEP = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.NUMBER_1000INT')
FORMAT_FLOAT_SEP = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.NUMBER_1000DEC2')
FORMAT_PERCENT_INT = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.PERCENT_INT')
FORMAT_PERCENT_FLOAT = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.PERCENT_DEC2')
FORMAT_DATE = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.DATE_SYSTEM_SHORT')
FORMAT_TIME = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.TIME_HHMM')
FORMAT_DATETIME = uno.getConstantByName('com.sun.star.i18n.NumberFormatIndex.DATETIME_SYSTEM_SHORT_HHMM')
# Font weight choices
FONT_WEIGHT_DONTKNOW = uno.getConstantByName('com.sun.star.awt.FontWeight.DONTKNOW')
FONT_WEIGHT_THIN = uno.getConstantByName('com.sun.star.awt.FontWeight.THIN')
FONT_WEIGHT_ULTRALIGHT = uno.getConstantByName('com.sun.star.awt.FontWeight.ULTRALIGHT')
FONT_WEIGHT_LIGHT = uno.getConstantByName('com.sun.star.awt.FontWeight.LIGHT')
FONT_WEIGHT_SEMILIGHT = uno.getConstantByName('com.sun.star.awt.FontWeight.SEMILIGHT')
FONT_WEIGHT_NORMAL = uno.getConstantByName('com.sun.star.awt.FontWeight.NORMAL')
FONT_WEIGHT_SEMIBOLD = uno.getConstantByName('com.sun.star.awt.FontWeight.SEMIBOLD')
FONT_WEIGHT_BOLD = uno.getConstantByName('com.sun.star.awt.FontWeight.BOLD')
FONT_WEIGHT_ULTRABOLD = uno.getConstantByName('com.sun.star.awt.FontWeight.ULTRABOLD')
FONT_WEIGHT_BLACK = uno.getConstantByName('com.sun.star.awt.FontWeight.BLACK')
# Text underline choices (only first three are present here)
UNDERLINE_NONE = uno.getConstantByName('com.sun.star.awt.FontUnderline.NONE')
UNDERLINE_SINGLE = uno.getConstantByName('com.sun.star.awt.FontUnderline.SINGLE')
UNDERLINE_DOUBLE = uno.getConstantByName('com.sun.star.awt.FontUnderline.DOUBLE')
# Text alignment choices
TEXT_ALIGN_STANDARD = 'STANDARD'
TEXT_ALIGN_LEFT = 'LEFT'
TEXT_ALIGN_CENTER = 'CENTER'
TEXT_ALIGN_RIGHT = 'RIGHT'
TEXT_ALIGN_BLOCK = 'BLOCK'
TEXT_ALIGN_REPEAT = 'REPEAT'
# Axis choices
AXIS_PRIMARY = uno.getConstantByName('com.sun.star.chart.ChartAxisAssign.PRIMARY_Y')
AXIS_SECONDARY = uno.getConstantByName('com.sun.star.chart.ChartAxisAssign.SECONDARY_Y')
# Exceptions thrown by UNO.
# We try to catch them and re-throw Python standard exceptions.
_IndexOutOfBoundsException = uno.getClass('com.sun.star.lang.IndexOutOfBoundsException')
_NoSuchElementException = uno.getClass('com.sun.star.container.NoSuchElementException')
_IOException = uno.getClass('com.sun.star.io.IOException')
_NoConnectException = uno.getClass('com.sun.star.connection.NoConnectException')
_ConnectionSetupException = uno.getClass('com.sun.star.connection.ConnectionSetupException')
UnoException = uno.getClass('com.sun.star.uno.Exception')
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
text_type = str
else:
string_types = basestring,
integer_types = (int, long)
text_type = unicode
range = xrange
def str_repr(klass):
"""
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
"""
if PY2:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
klass.__repr__ = lambda self: '<%s: %r>' % (self.__class__.__name__, str(self))
return klass
def _clean_slice(key, length):
"""
Validates and normalizes a cell range slice.
>>> _clean_slice(slice(None, None), 10)
(0, 10)
>>> _clean_slice(slice(-10, 10), 10)
(0, 10)
>>> _clean_slice(slice(-11, 11), 10)
(0, 10)
>>> _clean_slice(slice('x', 'y'), 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, str given.
>>> _clean_slice(slice(0, 10, 2), 10)
Traceback (most recent call last):
...
NotImplementedError: Cell slice with step is not supported.
>>> _clean_slice(slice(5, 5), 10)
Traceback (most recent call last):
...
ValueError: Cell slice can not be empty.
"""
if key.step is not None:
raise NotImplementedError('Cell slice with step is not supported.')
start, stop = key.start, key.stop
if start is None:
start = 0
if stop is None:
stop = length
if not isinstance(start, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(start).__name__)
if not isinstance(stop, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(stop).__name__)
if start < 0:
start = start + length
if stop < 0:
stop = stop + length
start, stop = max(0, start), min(length, stop)
if start == stop:
raise ValueError('Cell slice can not be empty.')
return start, stop
def _clean_index(key, length):
"""
Validates and normalizes a cell range index.
>>> _clean_index(0, 10)
0
>>> _clean_index(-10, 10)
0
>>> _clean_index(10, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(-11, 10)
Traceback (most recent call last):
...
IndexError: Cell index out of range.
>>> _clean_index(None, 10)
Traceback (most recent call last):
...
TypeError: Cell indices must be integers, NoneType given.
"""
if not isinstance(key, integer_types):
raise TypeError('Cell indices must be integers, %s given.' % type(key).__name__)
if -length <= key < 0:
return key + length
elif 0 <= key < length:
return key
else:
raise IndexError('Cell index out of range.')
def _row_name(index):
"""
Converts a row index to a row name.
>>> _row_name(0)
'1'
>>> _row_name(10)
'11'
"""
return '%d' % (index + 1)
def _col_name(index):
"""
Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA'
"""
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))
index -= limit
@str_repr
class SheetPosition(object):
"""
Position of a rectangular are in a spreadsheet.
This class represent physical position in 100/th mm,
see SheetAddress class for a logical address of cells.
>>> position = SheetPosition(1000, 2000)
>>> print position
x=1000, y=2000
>>> position = SheetPosition(1000, 2000, 3000, 4000)
>>> print position
x=1000, y=2000, width=3000, height=4000
"""
__slots__ = ('x', 'y', 'width', 'height')
def __init__(self, x, y, width=0, height=0):
self.x = x
self.y = y
self.width = width
self.height = height
def __str__(self):
if self.width == self.height == 0:
return u'x=%d, y=%d' % (self.x, self.y)
return u'x=%d, y=%d, width=%d, height=%d' % (self.x, self.y,
self.width, self.height)
def replace(self, x=None, y=None, width=None, height=None):
x = x if x is not None else self.x
y = y if y is not None else self.y
width = width if width is not None else self.width
height = height if height is not None else self.height
return self.__class__(x, y, width, height)
@classmethod
def _from_uno(cls, position, size):
return cls(position.X, position.Y, size.Width, size.Height)
def _to_uno(self):
struct = uno.createUnoStruct('com.sun.star.awt.Rectangle')
struct.X = self.x
struct.Y = self.y
struct.Width = self.width
struct.Height = self.height
return struct
@str_repr
class SheetAddress(object):
"""
Address of a cell or a rectangular range of cells in a spreadsheet.
This class represent logical address of cells, see SheetPosition
class for physical location.
>>> address = SheetAddress(1, 2)
>>> print address
$C$2
>>> address = SheetAddress(1, 2, 3, 4)
>>> print address
$C$2:$F$4
"""
__slots__ = ('row', 'col', 'row_count', 'col_count')
def __init__(self, row, col, row_count=1, col_count=1):
self.row, self.col = row, col
self.row_count, self.col_count = row_count, col_count
def __str__(self):
return self.formula(row_abs=True, col_abs=True)
@property
def row_end(self):
return self.row + self.row_count - 1
@property
def col_end(self):
return self.col + self.col_count - 1
def formula(self, row_abs=False, col_abs=False):
"""
Returns this address as a string to be used in formulas.
"""
if row_abs and col_abs:
fmt = u'$%s$%s'
elif row_abs:
fmt = u'%s$%s'
elif col_abs:
fmt = u'$%s%s'
else:
fmt = u'%s%s'
start = fmt % (_col_name(self.col), _row_name(self.row))
if self.row_count == self.col_count == 1:
return start
end = fmt % (_col_name(self.col_end), _row_name(self.row_end))
return '%s:%s' % (start, end)
def replace(self, row=None, col=None, row_count=None, col_count=None):
"""
Returns a new address which the specified fields replaced.
"""
row = row if row is not None else self.row
col = col if col is not None else self.col
row_count = row_count if row_count is not None else self.row_count
col_count = col_count if col_count is not None else self.col_count
return self.__class__(row, col, row_count, col_count)
@classmethod
def _from_uno(cls, target):
row_count = target.EndRow - target.StartRow + 1
col_count = target.EndColumn - target.StartColumn + 1
return cls(target.StartRow, target.StartColumn, row_count, col_count)
def _to_uno(self, sheet):
struct = uno.createUnoStruct('com.sun.star.table.CellRangeAddress')
struct.Sheet = sheet
struct.StartColumn = self.col
struct.StartRow = self.row
struct.EndColumn = self.col_end
struct.EndRow = self.row_end
return struct
class _UnoProxy(object):
"""
Abstract base class for objects which act as a proxy to UNO objects.
"""
__slots__ = ('_target',)
def __init__(self, target):
self._target = target
def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__,
self._target.getSupportedServiceNames())
class NamedCollection(_UnoProxy):
"""
Base class for collections accessible by both index and name.
"""
# Target must implement both of:
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/container/XIndexAccess.html
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/container/XNameAccess.html
__slots__ = ()
def __len__(self):
return self._target.getCount()
def __getitem__(self, key):
if isinstance(key, integer_types):
target = self._get_by_index(key)
return self._factory(target)
if isinstance(key, string_types):
target = self._get_by_name(key)
return self._factory(target)
raise TypeError('%s must be accessed either by index or name.'
% self.__class__.__name__)
# Internal:
def _factory(self, target):
raise NotImplementedError # pragma: no cover
def _get_by_index(self, index):
try:
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/container/XIndexAccess.html#getByIndex
return self._target.getByIndex(index)
except _IndexOutOfBoundsException:
raise IndexError(index)
def _get_by_name(self, name):
try:
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/container/XNameAccess.html#getByName
return self._target.getByName(name)
except _NoSuchElementException:
raise KeyError(name)
class DiagramSeries(_UnoProxy):
"""
Diagram series.
This class allows to control how one sequence of values (typically
one table column) is displayed in a chart (for example appearance
of one line).
"""
__slots__ = ()
def __get_axis(self):
"""
Gets to which axis this series are assigned.
"""
return self._target.getPropertyValue('Axis')
def __set_axis(self, value):
"""
Sets to which axis this series are assigned.
"""
self._target.setPropertyValue('Axis', value)
axis = property(__get_axis, __set_axis)
def __get_line_color(self):
"""
Gets line color.
"""
return self._target.getPropertyValue('LineColor')
def __set_line_color(self, value):
"""
Sets line color.
Be aware that this call is sometimes ignored by OpenOffice.
"""
self._target.setPropertyValue('LineColor', value)
line_color = property(__get_line_color, __set_line_color)
def __get_fill_color(self):
"""
Gets fill color.
"""
return self._target.getPropertyValue('FillColor')
def __set_fill_color(self, value):
"""
Sets fill color.
"""
self._target.setPropertyValue('FillColor', value)
fill_color = property(__get_fill_color, __set_fill_color)
class DiagramSeriesCollection(_UnoProxy):
"""
Provides access to individual diagram series.
Instance of this class is returned when series property of
the Diagram class is accessed.
"""
__slots__ = ()
# It seems that length of series can not be easily determined so
# here is no __len__ method.
def __getitem__(self, key):
try:
target = self._target.getDataRowProperties(key)
except _IndexOutOfBoundsException:
raise IndexError(key)
else:
return DiagramSeries(target)
class Axis(_UnoProxy):
"""
Chart axis
"""
__slots__ = ()
def __get_visible(self):
"""
Gets whether this axis is visible.
"""
# Getting target.HasXAxis is a lot of faster then accessing
# target.XAxis.Visible property.
return self._target.getPropertyValue(self._has_axis_property)
def __set_visible(self, value):
"""
Sets whether this axis is visible.
"""
return self._target.setPropertyValue(self._has_axis_property, value)
visible = property(__get_visible, __set_visible)
def __get_title(self):
"""
Gets title of this axis.
"""
target = self._get_title_target()
return target.getPropertyValue('String')
def __set_title(self, value):
"""
Sets title of this axis.
"""
# OpenOffice on Debian "squeeze" ignore value of target.XAxis.String
# unless target.HasXAxisTitle is set to True first. (Despite the
# fact that target.HasXAxisTitle is reported to be False until
# target.XAxis.String is set to non empty value.)
self._target.setPropertyValue(self._has_axis_title_property, True)
target = self._get_title_target()
target.setPropertyValue('String', text_type(value))
title = property(__get_title, __set_title)
def __get_logarithmic(self):
"""
Gets whether this axis has an logarithmic scale.
"""
target = self._get_axis_target()
return target.getPropertyValue('Logarithmic')
def __set_logarithmic(self, value):
"""
Sets whether this axis has an logarithmic scale.
"""
target = self._get_axis_target()
target.setPropertyValue('Logarithmic', value)
logarithmic = property(__get_logarithmic, __set_logarithmic)
def __get_reversed(self):
"""
Gets whether this axis is reversed
"""
target = self._get_axis_target()
return target.getPropertyValue('ReverseDirection')
def __set_reversed(self, value):
"""
Sets whether this axis is reversed
"""
target = self._get_axis_target()
return target.setPropertyValue('ReverseDirection', value)
reversed = property(__get_reversed, __set_reversed)
# The _target property of this class does not hold the axis itself but
# the owner diagram instance. So following methods and properties has
# to be overridden in order to access appropriate UNO objects.
_has_axis_property = None
_has_axis_title_property = None
def _get_axis_target(self):
raise NotImplementedError # pragma: no cover
def _get_title_target(self):
raise NotImplementedError # pragma: no cover
class XAxis(Axis):
__slots__ = ()
_has_axis_property = 'HasXAxis'
_has_axis_title_property = 'HasXAxisTitle'
def _get_axis_target(self):
return self._target.getXAxis()
def _get_title_target(self):
return self._target.getXAxisTitle()
class YAxis(Axis):
__slots__ = ()
_has_axis_property = 'HasYAxis'
_has_axis_title_property = 'HasYAxisTitle'
def _get_axis_target(self):
return self._target.getYAxis()
def _get_title_target(self):
return self._target.getYAxisTitle()
class SecondaryXAxis(Axis):
__slots__ = ()
_has_axis_property = 'HasSecondaryXAxis'
_has_axis_title_property = 'HasSecondaryXAxisTitle'
def _get_axis_target(self):
return self._target.getSecondaryXAxis()
def _get_title_target(self):
return self._target.getSecondXAxisTitle()
class SecondaryYAxis(Axis):
__slots__ = ()
_has_axis_property = 'HasSecondaryYAxis'
_has_axis_title_property = 'HasSecondaryYAxisTitle'
def _get_axis_target(self):
return self._target.getSecondaryYAxis()
def _get_title_target(self):
return self._target.getSecondYAxisTitle()
class Diagram(_UnoProxy):
"""
Diagram - inner content of a chart.
Each chart has a diagram which specifies how data are rendered.
The inner diagram can be changed or replaced while the
the outer chart instance is still the same.
"""
__slots__ = ()
@property
def series(self):
"""
Collection of diagram series.
"""
return DiagramSeriesCollection(self._target)
# Following code is specific to 2D diagrams. If support for another
# diagram types is added (e.g. pie) then a new class should
# be probably introduced.
@property
def x_axis(self):
"""
X (bottom) axis
"""
return XAxis(self._target)
@property
def y_axis(self):
"""
Y (left) axis
"""
return YAxis(self._target)
@property
def secondary_x_axis(self):
"""
Secondary X (top) axis
"""
return SecondaryXAxis(self._target)
@property
def secondary_y_axis(self):
"""
Secondary Y (right) axis
"""
return SecondaryYAxis(self._target)
def __get_is_stacked(self):
"""
Gets whether series of the diagram are stacked.
"""
return self._target.getPropertyValue('Stacked')
def __set_is_stacked(self, value):
"""
Sets whether series of the diagram are stacked.
"""
self._target.setPropertyValue('Stacked', value)
is_stacked = property(__get_is_stacked, __set_is_stacked)
class BarDiagram(Diagram):
"""
Bar or column diagram.
Type of diagram can be changed using Chart.change_type method.
"""
__slots__ = ()
_type = 'com.sun.star.chart.BarDiagram'
def __get_lines(self):
"""
Gets count of series which are rendered as lines instead of lines.
"""
return self._target.getPropertyValue('NumberOfLines')
def __set_lines(self, value):
"""
Sets count of series which are rendered as lines instead of lines
"""
return self._target.setPropertyValue('NumberOfLines', value)
lines = property(__get_lines, __set_lines)
def __get_is_horizontal(self):
"""
Gets whether this diagram is rendered with horizontal bars.
If value is False then you get vertical columns.
"""
# Be aware - this call is translated to UNO "Vertical" property.
#
# UNO API claims that if vertical is false then we get a column chart
# rather than a bar chart -- which describes OpenOffice behavior.
#
# But the words "horizontal" and "vertical" simply mean opposite
# of the UNO semantics. If you don't believe me then try to google
# for "horizontal bar chart" and "vertical bar chart" images.
return self._target.getPropertyValue('Vertical')
def __set_is_horizontal(self, value):
"""
Sets whether this diagram is rendered with horizontal bars.
"""
return self._target.setPropertyValue('Vertical', value)
is_horizontal = property(__get_is_horizontal, __set_is_horizontal)
def __get_is_grouped(self):
"""
Gets whether to group columns attached to different axis.
If bars of a bar or column chart are attached to different axis,
this property determines how to display those. If true, the bars
are grouped together in one block for each axis, thus they are
painted one group over the other.
"""
return self._target.getPropertyValue('GroupBarsPerAxis')
def __set_is_grouped(self, value):
"""
Sets whether to group columns attached to different axis.
"""
return self._target.setPropertyValue('GroupBarsPerAxis', value)
is_grouped = property(__get_is_grouped, __set_is_grouped)
class LineDiagram(Diagram):
"""
Line, spline or symbol diagram.
Type of diagram can be changed using Chart.change_type method.
"""
__slots__ = ()
_type = 'com.sun.star.chart.LineDiagram'
def __get_spline(self):
return self._target.getPropertyValue('SplineType')
def __set_spline(self, value):
self._target.setPropertyValue('SplineType', int(value))
spline = property(__get_spline, __set_spline)
# Registry of supported diagram types.
_DIAGRAM_TYPES = {
BarDiagram._type: BarDiagram,
LineDiagram._type: LineDiagram,
}
class Chart(_UnoProxy):
"""
Chart
"""
__slots__ = ('sheet', '_embedded')
def __init__(self, sheet, target):
self.sheet = sheet
# Embedded object provides most of the functionality it will be
# probably often needed -- cache it for better performance.
self._embedded = target.getEmbeddedObject()
super(Chart, self).__init__(target)
@property
def name(self):
"""
Chart name which can be used as a key for accessing this chart.
"""
return self._target.getName()
@property
def has_row_header(self):
"""
Returns whether the first row is used for header
"""
return self._target.getHasRowHeaders()
@property
def has_col_header(self):
"""
Returns whether the first column is used for header
"""
return self._target.getHasColumnHeaders()
@property
def ranges(self):
"""
Returns a list of addresses with source data.
"""
ranges = self._target.getRanges()
return map(SheetAddress._from_uno, ranges)
@property
def diagram(self):
"""
Diagram - inner content of this chart.
The diagram can be replaced by another type using change_type method.
"""
target = self._embedded.getDiagram()
target_type = target.getDiagramType()
cls = _DIAGRAM_TYPES.get(target_type, Diagram)
return cls(target)
def change_type(self, cls):
"""
Change type of diagram in this chart.
Accepts one of classes which extend Diagram.
"""
target_type = cls._type
target = self._embedded.createInstance(target_type)
self._embedded.setDiagram(target)
return cls(target)
class ChartCollection(NamedCollection):
"""
Collection of charts in one sheet.
"""
__slots__ = ('sheet',)
def __init__(self, sheet, target):
self.sheet = sheet
super(ChartCollection, self).__init__(target)
def __delitem__(self, key):
if not isinstance(key, string_types):
key = self[key].name
self._delete(key)
def create(self, name, position, ranges=(), col_header=False, row_header=False):
"""
Creates and inserts a new chart.
"""
rect = self._uno_rect(position)
ranges = self._uno_ranges(ranges)
self._create(name, rect, ranges, col_header, row_header)
return self[name]
# Internal:
def _factory(self, target):
return Chart(self.sheet, target)
def _uno_rect(self, position):
if isinstance(position, CellRange):
position = position.position
return position._to_uno()
def _uno_ranges(self, ranges):
if not isinstance(ranges, (list, tuple)):
ranges = [ranges]
return tuple(map(self._uno_range, ranges))
def _uno_range(self, address):
if isinstance(address, CellRange):
address = address.address
return address._to_uno(self.sheet.index)
def _create(self, name, rect, ranges, col_header, row_header):
# http://www.openoffice.org/api/docs/common/ref/com/sun/star/table/XTableCharts.html#addNewByName
self._target.addNewByName(name, rect, ranges, col_header, row_header)
def _delete(self, name):
try:
self._target.removeByName(name)
except _NoSuchElementException:
raise KeyError(name)
class SheetCursor(_UnoProxy):
"""
Cursor in spreadsheet sheet.
Most of spreadsheet operations are done using this cursor
because cursor movement is much faster then cell range selection.
"""
__slots__ = ('row', 'col', 'row_count', 'col_count',
'max_row_count', 'max_col_count')
def __init__(self, target):
# Target must be com.sun.star.sheet.XSheetCellCursor
ra = target.getRangeAddress()
self.row = 0
self.col = 0
self.row_count = ra.EndRow + 1
self.col_count = ra.EndColumn + 1
# Default cursor contains all the cells.
self.max_row_count = self.row_count
self.max_col_count = self.col_count
super(SheetCursor, self).__init__(target)
def get_target(self, row, col, row_count, col_count):
"""
Moves cursor to the specified position and returns in.
"""
# This method is called for almost any operation so it should
# be maximally optimized.
#
# Any comparison here is negligible compared to UNO call. So we do all
# possible checks which can prevent an unnecessary cursor movement.
#
# Generally we need to expand or collapse selection to the desired
# size and move it to the desired position. But both of these actions
# can fail if there is not enough space. For this reason we must
# determine which of the actions has to be done first. In some cases
# we must even move the cursor twice (cursor movement is faster than
# selection change).
#
target = self._target
# If we cannot resize selection now then we must move cursor first.
if self.row + row_count > self.max_row_count or self.col + col_count > self.max_col_count:
# Move cursor to the desired position if possible.
row_delta = row - self.row if row + self.row_count <= self.max_row_count else 0
col_delta = col - self.col if col + self.col_count <= self.max_col_count else 0
target.gotoOffset(col_delta, row_delta)
self.row += row_delta
self.col += col_delta
# Resize selection
if (row_count, col_count) != (self.row_count, self.col_count):
target.collapseToSize(col_count, row_count)
self.row_count = row_count
self.col_count = col_count
# Move cursor to the desired position
if (row, col) != (self.row, self.col):
target.gotoOffset(col - self.col, row - self.row)
self.row = row
self.col = col
return target
@str_repr
class CellRange(object):
"""
Range of cells in one sheet.
This is an abstract base class implements cell manipulation functionality.
"""
# Does not extend _UnoProxy because it uses sheet cursor internally
# instead of direct reference to UNO object.
__slots__ = ('sheet', 'address')
def __init__(self, sheet, address):
self.sheet = sheet
self.address = address
def __str__(self):
return text_type(self.address)
@property
def position(self):
"""
Physical position of this cells.
"""
target = self._get_target()
position, size = target.getPropertyValues(('Position', 'Size'))
return SheetPosition._from_uno(position, size)
def __get_is_merged(self):
"""
Gets whether cells are merged.
"""
return self._get_target().getIsMerged()
def __set_is_merged(self, value):
"""
Sets whether cells are merged.
"""
self._get_target().merge(value)
is_merged = property(__get_is_merged, __set_is_merged)
def __get_number_format(self):
"""
Gets format of numbers in this cells.
"""
return self._get_target().getPropertyValue('NumberFormat')