2 Utilities to handle worksheets
4 Copyright 2020 by Massimo Del Fedele
8 from com.sun.star.xml
import AttributeData
9 from com.sun.star.beans
import PropertyValue
10 from com.sun.star.util
import SortField
14 import LeenoDialogs
as DLG
16 from datetime
import date
19 User defined attributes handling in worksheets
20 Not supporting (by now) namespaces, it allows to
21 insert strings attributes into spreadsheets
25 userAttributes = oSheet.UserDefinedAttributes
26 attr = AttributeData()
29 if userAttributes.hasByName(name):
30 userAttributes.replaceByName(name, attr)
32 userAttributes.insertByName(name, attr)
33 oSheet.UserDefinedAttributes = userAttributes
36 userAttributes = oSheet.UserDefinedAttributes
37 if userAttributes.hasByName(name):
38 return userAttributes.getByName(name).Value
42 userAttributes = oSheet.UserDefinedAttributes
43 return userAttributes.hasByName(name)
46 userAttributes = oSheet.UserDefinedAttributes
47 if userAttributes.hasByName(name):
48 userAttributes.removeByName(name)
49 oSheet.UserDefinedAttributes = userAttributes
57 in un foglio cerca tutte le occorrenze delle chiavi
58 contenute in 'replaceDict' e le sostituisce con i rispettivi valori
60 replace = sheet.createReplaceDescriptor()
61 for key, val
in replaceDict.items():
62 replace.SearchString = key
69 replace.ReplaceString = val
70 sheet.replaceAll(replace)
78 given a sheet object returns containing document
79 sadly there's no built-in interface for it
80 and there's no simple way to do it...
83 attrName = str(random.random())
87 while oEnum.hasMoreElements():
88 oDoc = oEnum.nextElement()
92 while idx < sheets.Count:
110 check if sheet is the current one in its document
113 contr = oDoc.CurrentController
114 return contr.ActiveSheet.Name == oSheet.Name
122 contr = oDoc.CurrentController
123 contr.ActiveSheet = oSheet
128 set the active sheet in given document
130 contr = oDoc.CurrentController
131 return contr.ActiveSheet
139 dato il file legge i nomi dei fogli contenuti
147 res.append(sheet.Name)
158 crea una copia dello spreadsheet avente nome 'sourceName'
159 del documento 'oDoc' e lo mette in coda
162 nSheets = sheets.Count
163 if not sheets.hasByName(sourceName):
167 newName = sourceName +
'_' + str(int(random.random() * 10000))
168 if not sheets.hasByName(newName):
170 sheets.copyByName(sourceName, newName, nSheets)
171 newSheet = sheets.getByName(newName)
174 oldSheet = sheets.getByName(sourceName)
175 newSheet.TitleRows = oldSheet.TitleRows
176 newSheet.PrintTitleRows = oldSheet.PrintTitleRows
177 newSheet.PrintAreas = oldSheet.PrintAreas
187 copy a page style to a given document
188 (or make properties identical if name already present)
190 styleName = style.Name
191 nPageStyles = nDoc.StyleFamilies.getByName(
'PageStyles')
193 if nPageStyles.hasByName(styleName):
195 nPageStyle = nPageStyles.getByName(styleName)
198 nPageStyle = nDoc.createInstance(
'com.sun.star.style.PageStyle')
201 nPageStyles.insertByName(styleName, nPageStyle)
204 propSetInfo = style.PropertySetInfo
205 props = propSetInfo.Properties
208 nPageStyle.setPropertyValue(name, style.getPropertyValue(name))
211 nPageStyle.setPropertyValue(
'PageScale', style.getPropertyValue(
'PageScale'))
215 if oTxt.String.find(
'[PAGINA]') >= 0:
216 oField = oDoc.createInstance(
"com.sun.star.text.TextField.PageNumber")
219 if oTxt.String.find(
'[PAGINE]') >= 0:
220 oField = oDoc.createInstance(
"com.sun.star.text.TextField.PageCount")
224 def pdfExport(oDoc, sheets, destPath, HeaderFooter=None, coverBuilder = None):
226 export a sequence of spreadsheets to a PDF file
227 coverBuilder(oDoc, nDoc) takes current document as parameter, the
228 print document and adds a cover to the latter at end
229 if coverBuilder is None, no cover will be added
236 if coverBuilder
is not None:
237 hasCover = coverBuilder(oDoc, nDoc)
245 styleSet.add(sheet.PageStyle)
247 pageStyles = oDoc.StyleFamilies.getByName(
'PageStyles')
248 for styleName
in styleSet:
249 style = pageStyles.getByName(styleName)
256 pos = nDoc.Sheets.Count
257 nDoc.Sheets.importSheet(oDoc, sheet.Name, pos)
258 nDoc.Sheets[pos].PageStyle = sheet.PageStyle
259 if len(sheet.PrintAreas) > 0:
260 nDoc.Sheets[pos].PrintAreas = sheet.PrintAreas
261 nDoc.Sheets.removeByName(nDoc.Sheets[0].Name)
268 pageStyles = nDoc.StyleFamilies.getByName(
'PageStyles')
270 for sheet
in nDoc.Sheets:
271 styleSet.add(sheet.PageStyle)
272 for styleName
in styleSet:
273 pageStyle = pageStyles.getByName(styleName)
277 pageStyle.FirstPageNumber = 0
279 if pageStyle.HeaderIsOn:
281 left = HeaderFooter.get(
'intSx',
'')
282 center = HeaderFooter.get(
'intCenter',
'')
283 right = HeaderFooter.get(
'intDx',
'')
284 print(
" Left :", left)
285 print(
" Center:", center)
286 print(
" Right :", right)
287 content = pageStyle.LeftPageHeaderContent
288 content.LeftText.String = left
289 content.CenterText.String = center
290 content.RightText.String = right
297 pageStyle.RightPageHeaderContent = content
299 if pageStyle.FooterIsOn:
301 left = HeaderFooter.get(
'ppSx',
'')
302 center = HeaderFooter.get(
'ppCenter',
'')
303 right = HeaderFooter.get(
'ppDx',
'')
304 print(
" Left :", left)
305 print(
" Center:", center)
306 print(
" Right :", right)
307 content = pageStyle.LeftPageFooterContent
308 content.LeftText.String = left
309 content.CenterText.String = center
310 content.RightText.String = right
317 pageStyle.RightPageFooterContent = content
320 'FilterName':
'calc_pdf_Export',
323 destUrl = uno.systemPathToFileUrl(destPath)
333 freeze row and column up to row and col
335 Sadly it must use the controller, so it can't be
336 done headless... but we try to preserve all we can
342 controller = oDoc.CurrentController
353 controller.freezeAtPosition(row, col)
356 if curSheet
is not None:
365 colore { integer } : id colore
366 attribuisce al tab del foglio oSheet un colore a scelta
368 oSheet.TabColor = color
375 Restituisce l'indirizzo dell' area usata nello spreadsheet
376 in forma di oggetto CellRangeAddress
378 Sheet numero intero indice dello Sheet contenente l'area
379 occhio che è un indice, NON un oggetto spreadsheet
385 oCell = oSheet.getCellByPosition(0, 0)
386 oCursor = oSheet.createCursorByRange(oCell)
387 oCursor.gotoEndOfUsedArea(
True)
388 aAddress = oCursor.RangeAddress
393 ''' l'ultima riga usata nello spreadsheet '''
398 ''' l'ultima colonna usata nello spreadsheet '''
405 sString { string } : stringa da cercare
406 nCol { integer } : indice di colonna
408 start { integer } : riga di partenza
409 equal { integer } : se equal = 1 fa una ricerca per cella intera
411 Trova la prima ricorrenza di una stringa(sString) nella
412 colonna nCol di un foglio di calcolo(oSheet) e restituisce
415 oCell = oSheet.getCellByPosition(0, 0)
416 oCursor = oSheet.createCursorByRange(oCell)
417 oCursor.gotoEndOfUsedArea(
True)
418 aAddress = oCursor.RangeAddress
420 righe = range(start, aAddress.EndRow + 1)
422 righe = reversed (righe)
424 if equal == 1
and oSheet.getCellByPosition(nCol, nRow).String == sString:
426 if equal == 0
and sString
in oSheet.getCellByPosition(nCol, nRow).String:
431 sString { string } : stringa da cercare
432 nCol { integer } : indice di colonna
434 start { integer } : riga di partenza
436 Trova tutte le ricorrenze di una stringa (sString) nella
437 colonna nCol di un foglio di calcolo (oSheet) e restituisce
440 oCell = oSheet.getCellByPosition(0, 0)
441 oCursor = oSheet.createCursorByRange(oCell)
442 oCursor.gotoEndOfUsedArea(
True)
443 aAddress = oCursor.RangeAddress
445 for nRow
in range(start, aAddress.EndRow + 1):
446 if sString.upper()
in oSheet.getCellByPosition(nCol, nRow).String.upper():
447 ricorrenze.append(nRow)
452 sString { string } : stringa da cercare
455 Trova la prima ricorrenza di una stringa(sString) riga
456 per riga in un foglio di calcolo(oSheet) e restituisce
457 una tupla(IDcolonna, IDriga)
459 oCell = oSheet.getCellByPosition(0, 0)
460 oCursor = oSheet.createCursorByRange(oCell)
461 oCursor.gotoEndOfUsedArea(
True)
462 aAddress = oCursor.RangeAddress
463 righe = range (0, aAddress.EndRow + 1)
465 righe = reversed (righe)
468 for nCol
in range(0, aAddress.EndColumn + 1):
470 if sString
in oSheet.getCellByPosition(nCol, nRow).String:
477 create a sort field to be used in sortColumns()
478 column is the column to sort for (integer)
479 sortAscending is a boolean
481 oSortField = SortField()
482 oSortField.Field = column
483 oSortField.SortAscending = sortAscending
489 sort a range of cells based on given sortFields
490 sortfields are given by a tuple
491 so you can order by more criterions
493 oSortDesc = [PropertyValue()]
494 oSortDesc[0].Name =
"SortFields"
495 oSortDesc[0].Value = uno.Any(
"[]com.sun.star.util.SortField", sortFields)
496 oRange.sort(oSortDesc)
501 simple sort of a range by a column
502 sort direction given by 'sortAscending'
513 Definisce o ridefinisce un'area di dati a cui far riferimento
514 sSheet = nome del foglio, es.: 'S5'
515 sRange = individuazione del range di celle, es.:'$B$89:$L$89'
516 sName = nome da attribuire all'area scelta, es.: "manodopera"
518 sPath =
"$'" + sSheet +
"'." + sRange
519 oRanges = oDoc.NamedRanges
520 oCellAddress = oDoc.Sheets.getByName(sSheet).getCellRangeByName(
'A1').getCellAddress()
521 if oRanges.hasByName(sName):
522 oRanges.removeByName(sName)
523 oRanges.addNewByName(sName, sPath, oCellAddress, 0)
531 Corregge i nomi di range dati che contengono '#' sostituendo con '_'
534 oRange = oDoc.NamedRanges
535 tNamedArea = oRange.ElementNames
536 for el
in tNamedArea:
538 aName = oRange.getByName(el).ReferredCells.AbsoluteName
539 sSheet = aName.split(
'.')[0][1:]
540 sRange = aName.split(
'.')[1]
541 sName = el.replace(
'#',
'_')
543 oDoc.NamedRanges.removeByName(el)
552 Mostra i salti di pagina dell'area di stampa definita.
559 oFrame = desktop.getCurrentFrame()
560 oProp = PropertyValue()
561 oProp.Name =
'PagebreakMode'
563 properties = (oProp, )
565 dispatchHelper = ctx.ServiceManager.createInstanceWithContext(
'com.sun.star.frame.DispatchHelper', ctx)
566 dispatchHelper.executeDispatch(oFrame,
".uno:PagebreakMode",
"", 0, properties)
574 serve per unire tanti fogli in un unico foglio
577 lista_fogli = oDoc.Sheets.ElementNames
578 if not oDoc.getSheets().hasByName(
'unione_fogli'):
579 sheet = oDoc.createInstance(
"com.sun.star.sheet.Spreadsheet")
580 unione = oDoc.Sheets.insertByName(
'unione_fogli', sheet)
581 unione = oDoc.getSheets().getByName(
'unione_fogli')
583 for el
in lista_fogli:
588 oSheet = oDoc.getSheets().getByName(el)
589 oRangeAddress = oSheet.getCellRangeByPosition(
592 oCellAddress = unione.getCellByPosition(
595 oSheet.copyRange(oCellAddress, oRangeAddress)
597 DLG.MsgBox(
'Unione dei fogli eseguita.',
'Avviso')
599 unione = oDoc.getSheets().getByName(
'unione_fogli')
600 DLG.MsgBox(
'Il foglio "unione_fogli" è già esistente, quindi non procedo.',
'Avviso!')
601 oDoc.CurrentController.setActiveSheet(unione)