NamedRanges.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
  2. #
  3. # This file is part of the LibreOffice project.
  4. #
  5. # This Source Code Form is subject to the terms of the Mozilla Public
  6. # License, v. 2.0. If a copy of the MPL was not distributed with this
  7. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. #
  9. import traceback
  10. import uno
  11. def GetNamedRanges():
  12. """Returns a list of the named ranges in the document.
  13. """
  14. try:
  15. desktop = XSCRIPTCONTEXT.getDesktop()
  16. model = desktop.getCurrentComponent()
  17. rangeNames = model.NamedRanges.ElementNames
  18. result = []
  19. for i in rangeNames:
  20. range = model.NamedRanges.getByName(i).Content
  21. result.append((i, range))
  22. return result
  23. except Exception as e:
  24. print("Caught Exception: " + str(e))
  25. tb = e.__traceback__
  26. traceback.print_tb(tb)
  27. return None
  28. def DefineNamedRange(sheet, x0, y0, width, height, name):
  29. """Defines a new (or replaces an existing) named range on a sheet,
  30. using zero-based absolute coordinates
  31. """
  32. desktop = XSCRIPTCONTEXT.getDesktop()
  33. model = desktop.getCurrentComponent()
  34. # FIXME: Is there some Python-callable API to turn a row and column into an A1 string?
  35. # This obviously works only for the first 26 columns.
  36. abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  37. content = "$" + sheet + "." + "$" + \
  38. abc[x0: x0+1] + "$" + str(y0+1) + ":" + "$" + abc[x0+width -
  39. 1: x0+width] + "$" + str(y0+height)
  40. position = uno.createUnoStruct('com.sun.star.table.CellAddress')
  41. position.Sheet = 0
  42. position.Column = 0
  43. position.Row = 0
  44. model.NamedRanges.addNewByName(name, content, position, 0)
  45. return None
  46. def DeleteNamedRange(name):
  47. try:
  48. desktop = XSCRIPTCONTEXT.getDesktop()
  49. model = desktop.getCurrentComponent()
  50. model.NamedRanges.removeByName(name)
  51. except Exception as e:
  52. print("Caught Exception: " + str(e))
  53. tb = e.__traceback__
  54. traceback.print_tb(tb)
  55. return None
  56. # vim: set shiftwidth=4 softtabstop=4 expandtab: