Search code examples
pythonfunctionadd-inuser-defined-functionslibreoffice-calc

Calling a python function from within LibreCalc


I have the following code inside a file called calculadora.py

def calcpy(numA,numB):
    return numA+numB

Which is the proper way of calling the function calcpy() from within LibreCalc? I'd like to put, say, in cell A1=calcpy(B1,C1) and obtain the result...

I've already put the python script in both /usr/lib/libreoffice/share/Scripts/python/ and /home/lucas/.config/libreoffice/4/user/Scripts/python, I can also see it under the menu Tools->Macro->Organize Macro->Python

enter image description here

... but I do not really know how to invoke that function.

I've read some posts where it was suggested to wrap the function inside Basic, such as this:

function calcpy(a as double, b as double) as double
    script = GetScript("calcpy")
    calcpy = script.invoke(Array(a, b), Array(), Array())
end function

... but whenever I do use =calcpy(5,4) I get an error saying: "BASIC runtime error. Sub-procedure or function procedure not defined."

Is this even possible? Is using Basic the proper way? Is there a more direct (elegant?) way of doing it?

Thanks,

Lucas


Solution

  • There is a good answer here: How can I call a Python macro in a cell formula in OpenOffice.Org Calc? In your case, the Basic code should be:

    function calcpy(a as double, b as double) as double
        Dim scriptPro As Object, myScript As Object
        scriptPro = ThisComponent.getScriptProvider()
        myScript = scriptPro.getScript( _
               "vnd.sun.star.script:calculadora.py$calcpy?language=Python&location=user")
        calcpy = myScript.invoke(Array(a, b), Array(), Array() )
    end function
    

    Yes, there is a more direct / elegant way: Create an Add-In.