summaryrefslogtreecommitdiffstats
path: root/scripting/examples/python
diff options
context:
space:
mode:
Diffstat (limited to 'scripting/examples/python')
-rw-r--r--scripting/examples/python/Capitalise.py96
-rw-r--r--scripting/examples/python/HelloWorld.py47
-rw-r--r--scripting/examples/python/InsertText.py65
-rw-r--r--scripting/examples/python/NamedRanges.py134
-rw-r--r--scripting/examples/python/SetCellColor.py53
-rw-r--r--scripting/examples/python/TableSample.py131
6 files changed, 526 insertions, 0 deletions
diff --git a/scripting/examples/python/Capitalise.py b/scripting/examples/python/Capitalise.py
new file mode 100644
index 000000000..64d29a513
--- /dev/null
+++ b/scripting/examples/python/Capitalise.py
@@ -0,0 +1,96 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
+def getNewString(theString):
+ """helper function
+ """
+ if (not theString):
+ return ""
+
+ # should we tokenize on "."?
+ if len(theString) >= 2 and theString[:2].isupper():
+ # first two chars are UC => first UC, rest LC
+ newString = theString[0].upper() + theString[1:].lower()
+
+ elif theString[0].isupper():
+ # first char UC => all to LC
+ newString = theString.lower()
+
+ else:
+ # all to UC.
+ newString = theString.upper()
+
+ return newString
+
+
+def capitalisePython():
+ """Change the case of the selected or current word(s).
+ If at least the first two characters are "UPpercase, then it is changed
+ to first char "Uppercase".
+ If the first character is "Uppercase", then it is changed to
+ all "lowercase".
+ Otherwise, all are changed to "UPPERCASE".
+ """
+ # The context variable is of type XScriptContext and is available to
+ # all BeanShell scripts executed by the Script Framework
+ xModel = XSCRIPTCONTEXT.getDocument()
+
+ # the writer controller impl supports the css.view.XSelectionSupplier
+ # interface
+ xSelectionSupplier = xModel.getCurrentController()
+
+ # see section 7.5.1 of developers' guide
+ xIndexAccess = xSelectionSupplier.getSelection()
+ count = xIndexAccess.getCount()
+
+ if(count >= 1): # ie we have a selection
+ i = 0
+
+ while i < count:
+ xTextRange = xIndexAccess.getByIndex(i)
+ theString = xTextRange.getString()
+ # print("theString")
+ if len(theString) == 0:
+ # sadly we can have a selection where nothing is selected
+ # in this case we get the XWordCursor and make a selection!
+ xText = xTextRange.getText()
+ xWordCursor = xText.createTextCursorByRange(xTextRange)
+
+ if not xWordCursor.isStartOfWord():
+ xWordCursor.gotoStartOfWord(False)
+
+ xWordCursor.gotoNextWord(True)
+ theString = xWordCursor.getString()
+ newString = getNewString(theString)
+
+ if newString:
+ xWordCursor.setString(newString)
+ xSelectionSupplier.select(xWordCursor)
+ else:
+ newString = getNewString(theString)
+ if newString:
+ xTextRange.setString(newString)
+ xSelectionSupplier.select(xTextRange)
+ i += 1
+
+
+# lists the scripts, that shall be visible inside OOo. Can be omitted, if
+# all functions shall be visible, however here getNewString shall be suppressed
+g_exportedScripts = capitalisePython,
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/scripting/examples/python/HelloWorld.py b/scripting/examples/python/HelloWorld.py
new file mode 100644
index 000000000..ed21b2008
--- /dev/null
+++ b/scripting/examples/python/HelloWorld.py
@@ -0,0 +1,47 @@
+# HelloWorld python script for the scripting framework
+
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
+def HelloWorldPython():
+ """Prints the string 'Hello World (in Python)' into the current document.
+ """
+
+ # Get the doc from the scripting context which is made available to all
+ # scripts.
+ desktop = XSCRIPTCONTEXT.getDesktop()
+ model = desktop.getCurrentComponent()
+
+ # Check whether there's already an opened document.
+ # Otherwise, create a new one
+ if not hasattr(model, "Text"):
+ model = desktop.loadComponentFromURL(
+ "private:factory/swriter", "_blank", 0, ())
+
+ # get the XText interface
+ text = model.Text
+
+ # create an XTextRange at the end of the document
+ tRange = text.End
+
+ # and set the string
+ tRange.String = "Hello World (in Python)"
+
+ return None
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/scripting/examples/python/InsertText.py b/scripting/examples/python/InsertText.py
new file mode 100644
index 000000000..801b81908
--- /dev/null
+++ b/scripting/examples/python/InsertText.py
@@ -0,0 +1,65 @@
+# Example python script for the scripting framework
+
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
+def InsertText(text):
+ """Inserts the argument string into the current document.
+ If there is a selection, the selection is replaced by it.
+ """
+
+ # Get the doc from the scripting context which is made available to
+ # all scripts.
+ desktop = XSCRIPTCONTEXT.getDesktop()
+ model = desktop.getCurrentComponent()
+
+ # Check whether there's already an opened document.
+ if not hasattr(model, "Text"):
+ return
+
+ # The context variable is of type XScriptContext and is available to
+ # all BeanShell scripts executed by the Script Framework
+ xModel = XSCRIPTCONTEXT.getDocument()
+
+ # The writer controller impl supports the css.view.XSelectionSupplier
+ # interface.
+ xSelectionSupplier = xModel.getCurrentController()
+
+ # See section 7.5.1 of developers' guide
+ xIndexAccess = xSelectionSupplier.getSelection()
+ count = xIndexAccess.getCount()
+
+ if count >= 1: # ie we have a selection
+ i = 0
+
+ while i < count:
+ xTextRange = xIndexAccess.getByIndex(i)
+ theString = xTextRange.getString()
+
+ if not len(theString):
+ # Nothing really selected, just insert.
+ xText = xTextRange.getText()
+ xWordCursor = xText.createTextCursorByRange(xTextRange)
+ xWordCursor.setString(text)
+ xSelectionSupplier.select(xWordCursor)
+ else:
+ # Replace the selection.
+ xTextRange.setString(text)
+ xSelectionSupplier.select(xTextRange)
+
+ i += 1
diff --git a/scripting/examples/python/NamedRanges.py b/scripting/examples/python/NamedRanges.py
new file mode 100644
index 000000000..5a28e2b5d
--- /dev/null
+++ b/scripting/examples/python/NamedRanges.py
@@ -0,0 +1,134 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+import uno
+from com.sun.star.container import NoSuchElementException
+
+def DefineNamedRange(doc, SheetName, rangeName, rangeReference):
+ """Defines a new named range. If the named range exists in the document, then
+ update the rangeReference.
+
+ Example: DefineNamedRange(doc, "Sheet1", "test_range", '$A$1:$F$14').
+
+ API Reference:
+ https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1sheet_1_1XNamedRanges.html
+ """
+ aName = rangeName
+ # make sure the sheet name starts with "$"
+ sheetName = "$" + SheetName.replace("$", "")
+ aContent = sheetName + "." + rangeReference
+
+ try:
+ # If the named range exists, then update it
+ doc.NamedRanges.getByName(rangeName)
+ update = True
+ except NoSuchElementException:
+ update = False
+
+ if update:
+ doc.NamedRanges.getByName(rangeName).setContent(aContent)
+ else:
+ aPosition = uno.createUnoStruct('com.sun.star.table.CellAddress')
+ sheet = doc.Sheets.getByName(SheetName)
+ # the index of the sheet in the doc, 0-based
+ aPosition.Sheet = sheet.getRangeAddress().Sheet
+
+ addressObj = sheet.getCellRangeByName(rangeReference)
+ # (com.sun.star.table.CellRangeAddress){ Sheet = (short)0x0, StartColumn = (long)0x0, StartRow = (long)0x0, EndColumn = (long)0x5, EndRow = (long)0xd }
+ address = addressObj.getRangeAddress()
+
+ aPosition.Column = address.StartColumn
+ aPosition.Row = address.StartRow
+
+ doc.NamedRanges.addNewByName(aName, aContent, aPosition, 0)
+
+ return None
+
+def NamedRanges():
+ """The main function to be shown on the user interface."""
+ ctx = uno.getComponentContext()
+ smgr = ctx.ServiceManager
+ desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
+
+ # Create a blank spreadsheet document, instead of damaging the existing document.
+ doc = desktop.loadComponentFromURL("private:factory/scalc", "_blank", 0, ())
+
+ # Create a new sheet to store our output information
+ doc.Sheets.insertNewByName("Information", 1)
+ infoSheet = doc.Sheets.getByName("Information")
+
+ # Set text in the information sheet
+ infoSheet.getCellRangeByName("A1").String = "Operation"
+ infoSheet.getCellRangeByName("B1").String = "Name of Cell Range"
+ infoSheet.getCellRangeByName("C1").String = "Content of Named Cell Range"
+
+ # Format the information header row
+ infoHeaderRange = infoSheet.getCellRangeByName("A1:C1")
+ # 2 = CENTER, see enum CellHoriJustify in https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1table.html
+ infoHeaderRange.HoriJustify = 2
+ infoHeaderRange.CellBackColor = 0xdee6ef
+
+ # Defines the named range test_range1
+ dataSheetName = "data"
+ doc.Sheets[0].Name = dataSheetName
+ DefineNamedRange(doc, dataSheetName, "test_range1", "$A$1:$F$14")
+
+ # Displays the named range information
+ test_range1 = doc.NamedRanges.getByName("test_range1")
+ infoSheet.getCellRangeByName("A2").String = "Defined test_range1"
+ infoSheet.getCellRangeByName("B2").String = test_range1.Name
+ infoSheet.getCellRangeByName("C2").String = test_range1.Content
+
+ # Revise the named ranges.
+ DefineNamedRange(doc, dataSheetName, "test_range1", "$A$1:$A$10")
+ infoSheet.getCellRangeByName("A3").String = "Revised test_range1"
+ infoSheet.getCellRangeByName("B3").String = test_range1.Name
+ infoSheet.getCellRangeByName("C3").String = test_range1.Content
+
+ # Defines the named range test_range2
+ DefineNamedRange(doc, dataSheetName, "test_range2", "$B$1:$B$10")
+ test_range2 = doc.NamedRanges.getByName("test_range2")
+ infoSheet.getCellRangeByName("A4").String = "Defined test_range2"
+ infoSheet.getCellRangeByName("B4").String = test_range2.Name
+ infoSheet.getCellRangeByName("C4").String = test_range2.Content
+
+ # Set data to test_range1 and test_range2
+
+ dataSheet = doc.Sheets.getByName(dataSheetName)
+ # You should use a tuple for setDataArray. For range e.g. A1:E1 it should
+ # be in the form tuple((1,2,3,4,5)), and for range e.g. A1:A5 it should be
+ # in the form tuple((1,), (2,), (3,), (4,), (5,)).
+ data1 = tuple(((1,),(2,),(3,),(4,),(5,),(6,),(7,),(8,),(9,),(10,)))
+ dataSheet.getCellRangeByName(test_range1.Content).setDataArray(data1)
+ infoSheet.getCellRangeByName("A5").String = "Set value to test_range1"
+
+ data2 = tuple(((2,),(4,),(6,),(8,),(10,),(12,),(14,),(16,),(18,),(20,)))
+ dataSheet.getCellRangeByName(test_range2.Content).setDataArray(data2)
+ infoSheet.getCellRangeByName("A6").String = "Set value to test_range2"
+
+ # Calculate sum of test_range1
+ infoSheet.getCellRangeByName("A8").String = "Sum of test_range1:"
+ infoSheet.getCellRangeByName("B8").Formula = "=SUM(test_range1)"
+
+ # Calculate sum of test_range2
+ infoSheet.getCellRangeByName("A9").String = "Sum of test_range2:"
+ infoSheet.getCellRangeByName("B9").Formula = "=SUM(test_range2)"
+
+ # Calculate the difference between the two ranges
+ infoSheet.getCellRangeByName("A10").String = "sum(test_range2) - sum(test_range1):"
+ infoSheet.getCellRangeByName("B10").Formula = "=B9-B8"
+
+ # Format the sum header columns
+ infoSheet.getCellRangeByName("A8:A10").CellBackColor = 0xdee6ef
+
+ # Set column width
+ infoSheet.Columns.getByName("A").Width = 5590
+ infoSheet.Columns.getByName("B").Width = 4610
+ infoSheet.Columns.getByName("C").Width = 4610
+
+g_exportedScripts = (NamedRanges,)
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/scripting/examples/python/SetCellColor.py b/scripting/examples/python/SetCellColor.py
new file mode 100644
index 000000000..7319d621d
--- /dev/null
+++ b/scripting/examples/python/SetCellColor.py
@@ -0,0 +1,53 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+import uno
+
+def _SetCellColor(sheet, cellRange, color):
+ """Sets the background of 'cellRange' in 'sheet', to 'color'."""
+ # https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1table_1_1XCellRange.html#a92c77dc3025ac50d55bf31bc80ab118f
+ cells = sheet.getCellRangeByName(cellRange)
+
+ # https://api.libreoffice.org/docs/idl/ref/servicecom_1_1sun_1_1star_1_1table_1_1CellProperties.html
+ cells.CellBackColor = color
+
+def SetCellColor():
+ ctx = uno.getComponentContext()
+ smgr = ctx.ServiceManager
+ desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
+
+ # Create a blank spreadsheet document, instead of operating on the existing one
+ doc = desktop.loadComponentFromURL("private:factory/scalc", "_blank", 0, ())
+
+ # Select the first sheet in the spreadsheet (0-index based).
+ sheet = doc.Sheets[0]
+
+ # Call the above helper function to set color (in hex number).
+ # To get the hex number:
+ # 1. go to Calc, click toolbar dropdown "Background Color" > Custom Color;
+ # 2. Pick a color, copy the hex number and prefix it with "0x".
+ _SetCellColor(sheet, "C3:C21", 0x4021c9)
+ _SetCellColor(sheet, "D18:E21", 0x4021c9)
+ _SetCellColor(sheet, "G3:G21", 0x4021c9)
+ _SetCellColor(sheet, "H3:I5", 0x4021c9)
+ _SetCellColor(sheet, "I6:I21", 0x4021c9)
+ _SetCellColor(sheet, "H19:H21", 0x4021c9)
+
+ # You should get a nice "LO" in the spreadsheet!
+
+# Only the specified function will show in the Tools > Macro > Organize Macro dialog:
+g_exportedScripts = (SetCellColor,)
diff --git a/scripting/examples/python/TableSample.py b/scripting/examples/python/TableSample.py
new file mode 100644
index 000000000..0920bf8ad
--- /dev/null
+++ b/scripting/examples/python/TableSample.py
@@ -0,0 +1,131 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
+import uno
+
+# a UNO struct later needed to create a document
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
+from com.sun.star.awt import Size
+
+
+def insertTextIntoCell(table, cellName, text, color):
+ tableText = table.getCellByName(cellName)
+ cursor = tableText.createTextCursor()
+
+ cursor.setPropertyValue("CharColor", color)
+ tableText.setString(text)
+
+
+def createTable():
+ """Creates a new writer document and inserts a table with some data
+ (also known as the SWriter sample).
+ """
+ ctx = uno.getComponentContext()
+ smgr = ctx.ServiceManager
+ desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
+
+ # open a writer document
+ doc = desktop.loadComponentFromURL(
+ "private:factory/swriter", "_blank", 0, ())
+
+ text = doc.Text
+ cursor = text.createTextCursor()
+ text.insertString(
+ cursor,
+ "The first line in the newly created text document.\n",
+ 0)
+ text.insertString(
+ cursor,
+ "Now we are in the second line\n",
+ 0)
+
+ # create a text table
+ table = doc.createInstance("com.sun.star.text.TextTable")
+
+ # with 4 rows and 4 columns
+ table.initialize(4, 4)
+
+ text.insertTextContent(cursor, table, 0)
+ rows = table.Rows
+
+ table.setPropertyValue("BackTransparent", uno.Bool(0))
+ table.setPropertyValue("BackColor", 13421823)
+ row = rows.getByIndex(0)
+ row.setPropertyValue("BackTransparent", uno.Bool(0))
+ row.setPropertyValue("BackColor", 6710932)
+
+ textColor = 16777215
+
+ insertTextIntoCell(table, "A1", "FirstColumn", textColor)
+ insertTextIntoCell(table, "B1", "SecondColumn", textColor)
+ insertTextIntoCell(table, "C1", "ThirdColumn", textColor)
+ insertTextIntoCell(table, "D1", "SUM", textColor)
+
+ table.getCellByName("A2").setValue(22.5)
+ table.getCellByName("B2").setValue(5615.3)
+ table.getCellByName("C2").setValue(-2315.7)
+ table.getCellByName("D2").setFormula("sum <A2:C2>")
+
+ table.getCellByName("A3").setValue(21.5)
+ table.getCellByName("B3").setValue(615.3)
+ table.getCellByName("C3").setValue(-315.7)
+ table.getCellByName("D3").setFormula("sum <A3:C3>")
+
+ table.getCellByName("A4").setValue(121.5)
+ table.getCellByName("B4").setValue(-615.3)
+ table.getCellByName("C4").setValue(415.7)
+ table.getCellByName("D4").setFormula("sum <A4:C4>")
+
+ cursor.setPropertyValue("CharColor", 255)
+ cursor.setPropertyValue("CharShadowed", uno.Bool(1))
+
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+ text.insertString(
+ cursor,
+ "This is a colored Text - blue with shadow\n",
+ 0)
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+
+ textFrame = doc.createInstance("com.sun.star.text.TextFrame")
+ textFrame.setSize(Size(15000, 400))
+ textFrame.setPropertyValue("AnchorType", AS_CHARACTER)
+
+ text.insertTextContent(cursor, textFrame, 0)
+
+ textInTextFrame = textFrame.getText()
+ cursorInTextFrame = textInTextFrame.createTextCursor()
+ textInTextFrame.insertString(
+ cursorInTextFrame,
+ "The first line in the newly created text frame.",
+ 0)
+ textInTextFrame.insertString(
+ cursorInTextFrame,
+ "\nWith this second line the height of the rame raises.",
+ 0)
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+
+ cursor.setPropertyValue("CharColor", 65536)
+ cursor.setPropertyValue("CharShadowed", uno.Bool(0))
+
+ text.insertString(cursor, "That's all for now !!", 0)
+
+
+g_exportedScripts = createTable,
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab: