Menu

[r5]: / trunk / excel_com.py  Maximize  Restore  History

Download this file

899 lines (770 with data), 32.0 kB

  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
import win32com.client
import win32com.client.dynamic
import win32api
from pywintypes import UnicodeType, TimeType
import numpy as np
import mso
#use C:\Python27\Lib\site-packages\win32com\client\makepy.py end import microsoft excel class first
#import win32com.client.constants
import inspect
####################################################################
#Keep in mind that the Excel Object Model has the following hierarchy: Application, WorkBook, Sheet, Range, and Cell.
#www.icodeguru.com/WebServer/Python-Programming-on-Win32/ch09.htm
#xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
#xlApp.ActiveWorkbook.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
#xlApp.Workbooks("Book1").Sheets("Sheet1").Cells(1,1).Value = "Python Rules!"
#xlApp.Workbooks(1).Sheets(1).Cells(1,1).Value = "Python Rules!"
#xlApp.Workbooks(1).Sheets(1).Cells(1,1).Value = "Python Rules!"
# xlBook = xlApp.Workbook(1)
# xlSheet = xlApp.Sheets(1)
# xlSheet.Cells(1,1).Value = "Python Rules!"
#xlBook.Sheets(1).Name
#'Sheet1'
#xlBook.Sheets[1].Name
#'Sheet1'
#Time
# import time
# now = time.time()
# now # how many seconds since 1970?
#923611182.35
# import pythoncom
# time_object = pythoncom.MakeTime(now)
# int(time_object) # can get the value back?BR> 923611182
# xlSheet.Cells(3,1).Value = time_object # ?r send it
# xlSheet.Cells(3,1).Value
#<time object at 188c080>
#
# myRange1 = xlSheet.Cells(4,1) # one-cell range
# myRange2 = xlSheet.Range("B5:C10") # excel notation
# myRange3 = xlSheet.Range(xlSheet.Cells(2,2), xlSheet.Cells(3,8))
#wksht_names = [xlBook.Sheets(i).Name for i in range(1,xlBook.Sheets.Count+1)]
#sheet.Range("C14", "D21").Value = vals
# xlBook.Sheets.Add(After=xlBook.Sheets(xlBook.Sheets.Count)).Name = sheet
#
#used = ws.UsedRange
#nrows = used.Row + used.Rows.Count - 1
#ncols = used.Column + used.Columns.Count - 1
###############################################################
class excel_com(object):
def connect(self):
#gencache.EnsureDispatch http://timgolden.me.uk/python/win32_how_do_i/generate-a-static-com-proxy.html
#THis will enshure morule created, so usage of win32com.client.constants will be possible (static proxy)
self.xlApp = win32com.client.gencache.EnsureDispatch("Excel.Application")
self.xlApp.ScreenUpdating=True
#Other possible ways:
#self.xlApp = win32com.client.dynamic.Dispatch('Excel.Application')
#self.xlApp = win32com.client.Dispatch('Excel.Application')#This require import of module first (static proxy)
self.show_app()
self.xlCategory=getattr(win32com.client.constants,'xlCategory')
self.xlSeries=getattr(win32com.client.constants,'xlSeries')
self.xlValue=getattr(win32com.client.constants,'xlValue')
self.xlPasteValues=getattr(win32com.client.constants,'xlPasteValues')
self.xlNone=getattr(win32com.client.constants,'xlNone')
self.xlTop=getattr(win32com.client.constants,'xlTop')
self.xlBottom=getattr(win32com.client.constants,'xlBottom')
self.xlLeft=getattr(win32com.client.constants,'xlLeft')
self.xlRight=getattr(win32com.client.constants,'xlRight')
self.debug=False
#*************************** App operations ***************************
def set_screen_updating(self,val):
assert val in [True, False]
self.xlApp.ScreenUpdating=val
def close_app(self):
del self.xlApp
def show_app(self):
self.xlApp.Visible = 1
def hide_app(self):
self.xlApp.Visible = 0
def CutCopyMode(self,mode):
self.xlApp.CutCopyMode = mode
#*************************** Workbook operations ***************************
def open_workbook(self):
self.xlBook = self.xlApp.Workbooks.Open(filename)
self.wb_open=True
def add_workbook(self):
self.xlBook = self.xlApp.Workbooks.Add()
self.wb_open=True
def save(self, newfilename=None):
if newfilename:
assert isinstance(newfilename, str)
self.filename = newfilename
#if self.debug:
# print "Saving file %s"%(newfilename)
try:
self.xlBook.SaveAs(newfilename)
result=True
except:
result=False
else:
try:
self.xlBook.Save()
result=True
except:
result=False
return result
def close_workbook(self):
#wb_name=self.xlBook.Name
#self.xlApp.Windows(wb_name).Activate()
#self.xlApp.ActiveWindow.Close(SaveChanges=0)
#self.xlApp.Windows(wb_name).Close(SaveChanges=0)
self.xlBook.Close(SaveChanges=0)
self.wb_open=False
#*************************** Sheet operations ***************************
def gridlines_off(self,sheet):
#DisplayGridlines = False
assert isinstance(sheet, str)
activesheet=self.xlApp.ActiveSheet.Name
if activesheet!=sheet:
self._activate_sheet(sheet)
self.xlApp.ActiveWindow.DisplayGridlines = False
if activesheet!=sheet:
self._activate_sheet(activesheet)
def _hide_sheet(self,sheet):
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
sht.Visible = False
def _add_sheet(self,name):
assert isinstance(name, str)
sheet=self.xlBook.Sheets.Add()
sheet.Name=name
def _activate_sheet(self,name):
assert isinstance(name, str)
#self.xlApp.Windows(name).Activate()
self.xlApp.Sheets(name).Select()
def delete_sheet(self,name):
assert isinstance(name, str)
self.xlBook.Sheets(name).Delete()
#*************************** Chart operations ***************************
def _set_3d_rotation(self,chrt,properties):
"""
ActiveSheet.Shapes("Chart 1").ThreeD.RotationX = 20
ActiveSheet.Shapes("Chart 1").ThreeD.RotationY = 140
ActiveSheet.Shapes("Chart 1").ThreeD.FieldOfView = 35
"""
if 'RotationX' in properties:
chrt.SeriesCollection(1).Format.ThreeD.RotationX=properties['RotationX']
if 'RotationY' in properties:
chrt.SeriesCollection(1).Format.ThreeD.RotationY =properties['RotationY']
if 'FieldOfView' in properties:
chrt.SeriesCollection(1).Format.ThreeD.FieldOfView =properties['FieldOfView']
def _add_3d_chart(self,sheet,Left=100, Width=375, Top=75, Height=225):
sht = self.xlBook.Worksheets(sheet)
chrt=sht.Shapes.AddChart().Chart
self._set_chart_type(chrt,'xlSurface')
chrt.ChartType=xlSurface
chrt.SetElement (mso.msoElementSeriesAxisTitleRotated)
return chrt
def _add_chart_ws(self,sheet,Left=100, Width=375, Top=75, Height=225):
#chrt=self.xlBook.Charts.Add()
#where=getattr(win32com.client.constants,'xlLocationAsObject')
#chrt=chrt.Location(Where=where, Name="data")
#return chrt
#exit()
sht = self.xlBook.Worksheets(sheet)
return sht.ChartObjects().Add(Left=Left, Width=Width, Top=Top, Height=Height).Chart
def _add_chart_text(self,chrt,txt,left=292.25,top=56.25,width=72,height=72):
"""
Allows to add text label to chart
"""
label=chrt.Shapes.AddLabel(mso.msoTextOrientationHorizontal, left,top,width,height )
label.TextFrame2.TextRange.Characters.Text = txt
def _set_chart_type(self,chrt,type):
assert (isinstance(type, str))
attr=getattr(win32com.client.constants,type)
chrt.ChartType=attr
if type=='xlColumnClustered':
#ActiveChart.ChartGroups(1).GapWidth = 60
chrt.ChartGroups(1).GapWidth = 10
#More on chartgroups http://stackoverflow.com/questions/19841561/excel-in-which-ways-can-one-create-chartgroups
def set_axes_crosses_left(self,chrt):
#Axes(xlCategory).Crosses = xlMinimum
chrt.Axes(self.xlCategory).Crosses = getattr(win32com.client.constants,'xlMinimum')
def set_x_logarithmic(self,chrt):
#ActiveChart.Axes(xlCategory).ScaleType = xlLogarithmic
xlLogarithmic=getattr(win32com.client.constants,'xlLogarithmic')
chrt.Axes(self.xlCategory).ScaleType = xlLogarithmic
def set_y_logarithmic(self,chrt):
#ActiveChart.Axes(xlValue).ScaleType = xlLogarithmic
xlLogarithmic=getattr(win32com.client.constants,'xlLogarithmic')
chrt.Axes(self.xlValue).ScaleType = xlLogarithmic
def set_chart_xvalue_labels_oruentation(self,chrt,orientation):
"""
ActiveChart.Axes(xlCategory).TickLabels.Orientation = xlTickLabelOrientationUpward
Other possible values for the Orienteration property are:
xlTickLabelOrientationAutomatic
xlTickLabelOrientationHorizontal
xlTickLabelOrientationDownward
xlTickLabelOrientationVertical
"""
try:
orientation=int(orientation)
except:
orientation=getattr(win32com.client.constants,orientation)
chrt.Axes(self.xlCategory).TickLabels.Orientation = orientation
def AxisBetweenCategories(self,chrt,type,val):
chrt.Axes(getattr(win32com.client.constants,type)).AxisBetweenCategories = val
def set_chart_ticklabels_numberformat(self,chrt,format):
if 'xnumformat' in format:
#print "xlCategory",format['xnumformat']
chrt.Axes(self.xlCategory).TickLabels.NumberFormat = r'#,##%s'%(format['xnumformat'])
if 'ynumformat' in format:
#print "xlValue",format['ynumformat']
chrt.Axes(self.xlValue).TickLabels.NumberFormat = r'#,##%s'%(format['ynumformat'])
def set_gridlines(self,chrt,format):
if 'xlCategory' in format:
if 'HasMajorGridlines' in format['xlCategory']:
chrt.Axes(self.xlCategory).HasMajorGridlines=format['xlCategory']['HasMajorGridlines']
if 'TickMarkSpacing' in format['xlCategory']:
chrt.Axes(self.xlCategory).TickMarkSpacing=format['xlCategory']['TickMarkSpacing']
if 'MajorUnit' in format['xlCategory']:
chrt.Axes(self.xlCategory).MajorUnit=format['xlCategory']['MajorUnit']
if 'xlValue' in format:
if 'HasMajorGridlines' in format['xlValue']:
chrt.Axes(self.xlValue).HasMajorGridlines=format['xlValue']['HasMajorGridlines']
if 'MajorUnit' in format['xlValue']:
chrt.Axes(self.xlValue).MajorUnit=format['xlValue']['MajorUnit']
if 'TickMarkSpacing' in format['xlValue']:
chrt.Axes(self.xlValue).TickMarkSpacing=format['xlValue']['TickMarkSpacing']
def set_chart_axis_minmax(self,chrt,data):
"""
ActiveChart.Axes(xlValue).MaximumScale = 10
ActiveChart.Axes(xlValue).MaximumScale = -40
ActiveChart.Axes(xlCategory).MinimumScale = 0.001
ActiveChart.Axes(xlCategory).MaximumScale = 100
"""
if 'xmin' in data:
chrt.Axes(self.xlCategory).MinimumScale=data['xmin']
if 'xmax' in data:
chrt.Axes(self.xlCategory).MaximumScale=data['xmax']
if 'ymin' in data:
chrt.Axes(self.xlValue).MinimumScale=data['ymin']
if 'ymax' in data:
chrt.Axes(self.xlValue).MaximumScale=data['ymax']
def set_chart_data(self,chrt,data):
"""
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.PlotArea.Select
ActiveChart.SeriesCollection(1).Name = "=psrr_group!$A$2"
ActiveChart.SeriesCollection(1).XValues = "=psrr_group!$B$1:$O$1"
ActiveChart.SeriesCollection(1).Values = "=psrr_group!$B$2:$O$2"
data - list of dicts in format:
'Name':
'Values'
'XValues'
'type'
"""
assert (isinstance(data, list))
for s in data:
series= chrt.SeriesCollection().NewSeries()
if 'type' in s:
type_num=getattr(win32com.client.constants,type)
series.ChartType=type_num
eval_val= self.evaluate(s['Name'])
if eval_val in [-2146826259,-2146826273]:#If evaluate function returned error
setattr(series,'Name','%s'%(s['Name']))
else:
setattr(series,'Name','%s'%(eval_val))
for attr in ['Values','XValues']:
if attr in s:
setattr(series,attr,"=%s"%(s[attr]))
if 'rgb' in s and s['rgb']!=None:
series.Format.Line.ForeColor.RGB = win32api.RGB(s['rgb'][0],s['rgb'][1],s['rgb'][2])
if 'data_labels' in s and s['data_labels']:
series.ApplyDataLabels()
def set_title(self,chrt,info):
"""
.HasTitle = True
.ChartTitle.Characters.Text = "Tools Sales for Qtr 1"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Month"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Sales"
"""
chrt.HasTitle = True
if 'title' in info:
chrt.ChartTitle.Characters.Text =info['title']
xlPrimary=getattr(win32com.client.constants,'xlPrimary')
if 'ytitle' in info:
chrt.Axes(self.xlValue, xlPrimary).HasTitle = True
chrt.Axes(self.xlValue, xlPrimary).AxisTitle.Characters.Text = info['ytitle']
if 'xtitle' in info:
chrt.Axes(self.xlCategory, xlPrimary).HasTitle = True
chrt.Axes(self.xlCategory, xlPrimary).AxisTitle.Characters.Text = info['xtitle']
if 'depth_title' in info:
#ActiveChart.Axes(xlSeries, xlPrimary).AxisTitle.Text = "depth"
#Selection.Format.TextFrame2.TextRange.Characters.Text = "depth"
chrt.Axes(self.xlSeries).HasTitle = True
chrt.Axes(self.xlSeries, xlPrimary).AxisTitle.Characters.Text = info['depth_title']
def set_legend(self,chrt,info):
"""
ActiveChart.ChartArea.Select
ActiveChart.Legend.Select
Selection.Delete
"""
if 'position' in info:
assert info['position'] in ['xlTop','xlBottom','xlLeft','xlRight','None']
if info['position']=='None':
chrt.Legend.Delete()
else:
chrt.Legend.Position=getattr(win32com.client.constants,info['position'])
#*************************** OLEObjects ***************************
def _insert_file(self,sheet,filename):
#self.xlApp.Workbooks.Open(Filename=filename)
sht = self.xlBook.Worksheets(sheet)
sht.OLEObjects().Add(Filename=filename,Link=False, DisplayAsIcon=True,IconLabel='config')
#sht.OLEObjects().Add(Filename=filename,Link=False, DisplayAsIcon=True,IconFileName=r"C:\Windows\Installer\{90140000-0011-0000-0000-0000000FF1CE}\xlicons.exe",IconIndex=0,IconLabel=filename)
#*************************** ***************************
def evaluate(self,strFormula):
return self.xlApp.Evaluate(strFormula)
def _columns_auto_fit(self,sheet,col1,col2=None):
assert isinstance(sheet, str)
#Cells.EntireColumn.AutoFit
#Columns("A:C").EntireColumn.AutoFit
sht = self.xlBook.Worksheets(sheet)
if col2==None:
assert (col1>0)
assert isinstance(col1, int)
col_str=self.colnum_to_letter(sheet,col1)
else:
assert (col1>0 and col2>0)
assert (isinstance(col1, int) and isinstance(col2, int))
col1=self.colnum_to_letter(sheet,col1)
col2=self.colnum_to_letter(sheet,col2)
col_str="%s:%s"%(col1,col2)
sht.Columns(col_str).EntireColumn.AutoFit()
def _select_range(self,sheet,row1, col1,row2, col2):
range=self._get_range_object(sheet,row1, col1,row2, col2)
range.Select()
def _copy_range(self,sheet,row1, col1,row2, col2):
range=self._get_range_object(sheet,row1, col1,row2, col2)
range.Copy()
def _past_values_range(self,sheet,row1, col1,row2, col2):
"""
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
"""
range=self._get_range_object(sheet,row1, col1,row2, col2)
range.PasteSpecial(Paste=self.xlPasteValues, Operation=self.xlNone, SkipBlanks=False, Transpose=False)
def _select_cells_col(self,sheet,row, col,numofcells):
assert isinstance(numofcells, int)
assert numofcells>0
self._select_range(sheet,row,col,row,col+numofcells-1)
def _merge_selection(self):
self.xlApp.Selection.Merge()
def _merge(self,sheet,row1, col1,row2, col2):
range=self._get_range_object(sheet,row1, col1,row2, col2)
range.Merge()
def _merge_cells_col(self,sheet,row, col,numofcells):
assert isinstance(numofcells, int)
assert numofcells>0
self._merge(sheet,row,col,row,col+numofcells-1)
def _colnum_to_letter(self,sheet,col):
return self.rowcol_to_cell(sheet,1,col,1).split('$')[1]
def colnum_to_letter(self,sheet,col): # col is 1 based
excelCol = str()
div = col
while div:
(div, mod) = divmod(div-1, 26) # will return (x, 0 .. 25)
excelCol = chr(mod + 65) + excelCol
return excelCol
def rowcol_to_cell(self,sheet,row,col,abs=0):
assert (isinstance(row, int) and isinstance(col, int))
assert (row>0 and col>0)
return "%s%s"%(self.colnum_to_letter(sheet,col),str(row))
def _rowcol_to_cell(self,sheet,row,col,abs=0):
assert (isinstance(row, int) and isinstance(col, int))
assert (row>0 and col>0)
if abs:
return str(self.xlBook.Worksheets[sheet].Cells(row,col).Address)
else:
return str(self.xlBook.Worksheets[sheet].Cells(row,col).Address.replace('$',''))
#*************************** GET ***************************
def _get_range_object(self,sheet,row1, col1,row2, col2):
assert (isinstance(row1, int) and isinstance(col1, int))
assert (isinstance(row2, int) and isinstance(col2, int))
assert (row1>0 and col1>0)
assert (row2>0 and col2>0)
assert isinstance(sheet, str)
assert row2>=row1
assert col2>=col1
sht = self.xlBook.Worksheets(sheet)
return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2))
def get_cell_value(self, sheet, row, col):
"Get value of one cell"
assert (isinstance(row, int) and isinstance(col, int))
assert (row>0 and col>0)
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
return sht.Cells(row, col).Value
def _get_range_value(self,sheet,row1, col1,row2, col2):
def numpyfixStrings(item):
if type(item) is UnicodeType:
return str(item)
else:
return item
f = np.vectorize(numpyfixStrings,otypes=[np.ndarray])
assert (isinstance(row1, int) and isinstance(col1, int))
assert (isinstance(row2, int) and isinstance(col2, int))
assert isinstance(sheet, str)
assert (row1>0 and col1>0)
assert (row2>0 and col2>0)
sht = self.xlBook.Worksheets(sheet)
return f(np.array(sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value))
#*************************** SET ***************************
def _set_sort(self,sheet,config):
"""
'full_range':range of all data
'range_list': list of columns
{'range':, 'order':}
where 'order':xlDescending,xlAscending
ActiveWorkbook.Worksheets("inv_cross1").Sort.SortFields.Add Key:=Range( _
"B2:B52"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
or
range.Sort(Key1=self.get_range(key_cell), Order1=1, Header=0, OrderCustom=1, MatchCase=False, Orientation=1)
"""
sht = self.xlBook.Worksheets(sheet)
xlSortOnValues=getattr(win32com.client.constants,'xlSortOnValues')
xlSortNormal=getattr(win32com.client.constants,'xlSortNormal')
for range in config['range_list']:
order=getattr(win32com.client.constants,range['order'])
sht.Sort.SortFields.Add(Key=sht.Range(range['range']),SortOn=xlSortOnValues,Order=order,DataOption= xlSortNormal)
sht.Sort.SetRange(sht.Range(config['full_range']))
sht.Sort.Header = getattr(win32com.client.constants,'xlNo')
sht.Sort.MatchCase = False
sht.Sort.Orientation=getattr(win32com.client.constants,'xlTopToBottom')
sht.Sort.SortMethod=getattr(win32com.client.constants,'xlPinYin')
sht.Sort.Apply()
def _set_cell_value(self, sheet, row, col, value):
"set value of one cell"
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(value, (str,int,float))
assert (row>0 and col>0)
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Value = value
return sht.Cells(row, col).Address
def _set_cell_comment(self, sheet, row, col, value):
"set comment of one cell"
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(value, str)
assert (row>0 and col>0)
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).AddComment()
sht.Cells(row, col).Comment.Visible = False
sht.Cells(row, col).Comment.Text(Text=value)
def set_row_range(self, sheet, row, first_col,last_col, data):
assert isinstance(data, list)
assert isinstance(sheet, str)
range=self._get_range_object(sheet,row,first_col, row,last_col)
range.Value = data
def _set_range_value(self,sheet,row1, col1,row2, col2,data,type='value'):
assert isinstance(data, list)
assert type in ['value','formula','array_formula']
range=self._get_range_object(sheet,row1,col1,row2, col2)
if type=='value':
try:
range.Value = data
except:
print "Data:"
print data
raise
elif type=='formula':
range.Formula = data
elif type=='array_formula':
range.FormulaArray = data
else:
self.e.print_error("Unsupported type %s"%(type))
def _set_cell_formula_array(self, sheet, row, col, value):
"set value of one cell"
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(value, (str,UnicodeType))
assert (row>0 and col>0)
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).FormulaArray = "=%s"%(value)
return sht.Cells(row, col).Address
def _set_cell_formula(self, sheet, row, col, value):
"set value of one cell"
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(value, str)
assert (row>0 and col>0)
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Formula = "=%s"%(value)
return sht.Cells(row, col).Address
def set_font_property(self, sheet, row, col,format):
"""
property:.Color,.Bold,.Italic
"""
assert isinstance(format, dict)
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
for property in format.keys():
if isinstance(format[property], str):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(sht.Cells(row, col).Font,property,value)
#sht.Cells(row, col).Font.Bold=True
def set_font_property_selection(self,format):
"""
property:.Color,.Bold,.Italic
"""
assert isinstance(format, dict)
for property in format.keys():
if isinstance(format[property], str):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(self.xlApp.Selection.Font,property,value)
def set_interior(self, sheet, row, col,format):
"""
background_property
property:.Pattern,.PatternColorIndex,.ThemeColor,.TintAndShade,.PatternTintAndShade
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
"""
assert isinstance(format, dict)
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
for property in format.keys():
if isinstance(format[property], str):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(sht.Cells(row, col).Interior,property,value)
def set_interior_selection(self, format):
"""
background_property
property:.Pattern,.PatternColorIndex,.ThemeColor,.TintAndShade,.PatternTintAndShade
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
"""
assert isinstance(format, dict)
for property in format.keys():
if isinstance(format[property], str):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(self.xlApp.Selection.Interior,property,value)
def set_cell_properties(self, sheet, row, col,format):
"""
property:.HorizontalAlignment,.VerticalAlignment,.WrapText,.Orientation,.AddIndent,.IndentLevel,.ShrinkToFit,.ReadingOrder, .MergeCells
properties:
HorizontalAlignment:xlCenter,xlGeneral,xlRight,xlLeft
VerticalAlignment:xlTop,xlCenter,xlBottom
Expected dictionaty structure:
{'property':'value'}
"""
assert isinstance(format, dict)
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
for property in format.keys():
if isinstance(format[property], str) and hasattr(win32com.client.constants,format[property]):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(sht.Cells(row, col),property,value)
def set_cell_properties_selection(self, format):
"""
property:.HorizontalAlignment,.VerticalAlignment,.WrapText,.Orientation,.AddIndent,.IndentLevel,.ShrinkToFit,.ReadingOrder, .MergeCells
properties:
HorizontalAlignment:xlCenter,xlGeneral,xlRight,xlLeft
VerticalAlignment:xlTop,xlCenter,xlBottom
Expected dictionaty structure:
{'property':'value'}
"""
assert isinstance(format, dict)
for property in format.keys():
if isinstance(format[property], str):
value=getattr(win32com.client.constants,format[property])
else:
value=format[property]
setattr(self.xlApp.Selection,property,value)
def set_cell_borders(self, sheet, row, col,format_data):
"""
Border types:xlEdgeTop,xlEdgeLeft,xlEdgeBottom,xlEdgeRight,xlDiagonalDown,xlDiagonalUp,xlInsideVertical,xlInsideHorizontal
.LineStyle:xlContinuous,xlNone,xlDouble
.Weight: xlThin,xlMedium,xlThick
.ColorIndex:0-black
Expected dictionaty structure:
{'one_of_border_types':{
'LineStyle':LineStyle
'Weight':Weight
'ColorIndex':ColorIndex
}
}
Example:format_data={'xlEdgeBottom':{'LineStyle':'xlContinuous'}}
"""
assert isinstance(format_data, dict)
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
sht = self.xlBook.Worksheets(sheet)
for edge_type in format_data.keys():
border=sht.Cells(row, col).Borders(getattr(win32com.client.constants,edge_type))
for attr in format_data[edge_type]:
setattr(border, attr, getattr(win32com.client.constants,format_data[edge_type][attr]))
def set_cell_borders_selection(self, format_data):
"""
Border types:xlEdgeTop,xlEdgeLeft,xlEdgeBottom,xlEdgeRight,xlDiagonalDown,xlDiagonalUp,xlInsideVertical,xlInsideHorizontal
.LineStyle:xlContinuous,xlNone,xlDouble
.Weight: xlThin,xlMedium,xlThick
.ColorIndex:0-black
Expected dictionaty structure:
{'one_of_border_types':{
'LineStyle':LineStyle
'Weight':Weight
'ColorIndex':ColorIndex
}
}
Example:format_data={'xlEdgeBottom':{'LineStyle':'xlContinuous'}}
"""
assert isinstance(format_data, dict)
for edge_type in format_data.keys():
border=self.xlApp.Selection.Borders(getattr(win32com.client.constants,edge_type))
for attr in format_data[edge_type]:
setattr(border, attr, getattr(win32com.client.constants,format_data[edge_type][attr]))
def _set_cell_validation(self,sheet, row, col,configuration):
"""
Validation.Add
Type:xlValidateList
AlertStyle:xlValidAlertStop
Operator:xlBetween
Formula1:"1,2,3,4"
"""
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
assert isinstance(configuration,dict)
sht = self.xlBook.Worksheets(sheet)
Type=getattr(win32com.client.constants,configuration['Type'])
AlertStyle=getattr(win32com.client.constants,configuration['AlertStyle'])
Operator=getattr(win32com.client.constants,configuration['Operator'])
validation=sht.Cells(row, col).Validation
validation.Delete()
try:
#validation.Add(Type=Type,AlertStyle=AlertStyle,Operator=Operator,Formula1=configuration['Formula1'])
validation.Add(Type=Type,AlertStyle=AlertStyle,Operator=Operator,Formula1=configuration['Formula1'])
except Exception, e:
print configuration
#print e
raise
for param in configuration['properties']:
setattr(validation,param,self.get_attr_value(configuration['properties'][param]))
def _set_cell_conditional_formatting(self,sheet, row, col,configuration):
"""
FormatConditions.Add
Operator:xlGreater,xlLess,xlBetween,xlEqual,xlNotEqual,xlNotBetween,xlGreaterEqual,xlLessEqual
Type:xlCellValue
Formula1:formula like "=1"
Formula2: formula like "=1"
configuration - dictionary. Keys:
Operator,Type,Formula1,Formula2,Font,Interior
"""
assert (row>0 and col>0)
assert (isinstance(row, int) and isinstance(col, int))
assert isinstance(sheet, str)
assert isinstance(configuration,dict)
# Range("J9").Select
# Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _
# Formula1:="=1"
# Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
# With Selection.FormatConditions(1).Font
# .Color = -16383844
# .TintAndShade = 0
# End With
# With Selection.FormatConditions(1).Interior
# .PatternColorIndex = xlAutomatic
# .Color = 13551615
# .TintAndShade = 0
# End With
# Selection.FormatConditions(1).StopIfTrue = False
sht = self.xlBook.Worksheets(sheet)
cell=sht.Cells(row, col)
xlType=getattr(win32com.client.constants,configuration['Type'])
xlOperator=getattr(win32com.client.constants,configuration['Operator'])
if 'Formula2' not in configuration:
cell.FormatConditions.Add(Type=xlType,Operator=xlOperator, Formula1=configuration['Formula1'])
else:
cell.FormatConditions.Add(Type=xlType,Operator=xlOperator, Formula1=configuration['Formula1'],Formula2=configuration['Formula2'])
cell.FormatConditions(cell.FormatConditions.Count).SetFirstPriority()
FormatConditions=cell.FormatConditions(1)
font=FormatConditions.Font
for param in configuration['Font'].keys():
setattr(font,param,self.get_attr_value(configuration['Font'][param]))
Interior=FormatConditions.Interior
for param in configuration['Interior'].keys():
setattr(Interior,param,self.get_attr_value(configuration['Interior'][param]))
FormatConditions.StopIfTrue = False
#**************************** Non Excel functions #****************************
def get_attr_value(self,param):
if isinstance(param, str) and hasattr(win32com.client.constants,param):
value=getattr(win32com.client.constants,param)
else:
value=param
return value
def fixStrings(self, aMatrix):
# converts all unicode strings and times
newmatrix = []
for row in aMatrix:
newrow = []
for cell in row:
if type(cell) is UnicodeType:
newrow.append(str(cell))
else:
newrow.append(cell)
newmatrix.append(newrow)
return newmatrix
def numpyfixStrings(self,item):
if type(item) is UnicodeType:
return str(item)
else:
return item
def main():
#Usage example
e=excel_com()
e.connect()
e.add_workbook()
sheet_name="Sheet1"
e._insert_file(sheet_name,r"C:\Users\stepanov\Documents\projects\R31\LDRV\test\core\calibration.txt")
e.gridlines_off(sheet_name)
sheet_name="Sheet2"
e._activate_sheet(sheet_name)
chrt=e._add_chart_ws(sheet_name)
e.set_chart_type(chrt,'xlXYScatterSmoothNoMarkers')
e._select_range(sheet_name,1,1,1,3)
e._merge_selection()
e._set_cell_value(sheet_name,1,1,"Test table")
data=[
['Col1','Col2','Col3'],
[1,5,2],
[2,4,3],
[3,3,4],
[4,2,5]
]
e._set_range_value(sheet_name,2, 1,6, 3,data,'value')
e._set_cell_value(sheet_name,1,6,"Test table")
e._set_range_value(sheet_name,row1=2, col1=6,row2=6, col2=8,data=data,type='value')
data=[]
data.append({'Name':"aaa",'Values':'Sheet2!$B$3:$B$6','XValues':"Sheet2!$A$3:$A$6"})
data.append({'Name':"bbb",'Values':'Sheet2!$C$3:$C$6','XValues':"Sheet2!$A$3:$A$6"})
e.set_chart_data(chrt,data)
e._add_chart_text(chrt,'test')
sort_config={
'full_range':'F2:H6',
'range_list':[{'range':'G2:G6','order':'xlAscending'},{'range':'H2:H6','order':'xlAscending'}]
}
e._set_sort(sheet_name,sort_config)
if __name__=="__main__":
main()
exit(0)