Ayuda de LibreOffice 24.8
El servicio ScriptForge.Basic ofrece una colección de métodos de LibreOffice BASIC que ejecutar en un contexto Python. Los métodos del servicio Basic reproducen con exactitud la sintaxis y el comportamiento de las funciones incorporadas de BASIC.
Ejemplo típico:
   bas.MsgBox('Display this text in a message box from a Python script')
  El uso del servicio ScriptForge.Basic está limitado a las secuencias Python.
Antes de utilizar el servicio Basic, importe el método CreateScriptService() del módulo scriptforge:
    from scriptforge import CreateScriptService
    bas = CreateScriptService("Basic")
  | Nombre | De solo lectura | Tipo | Descripción | 
|---|---|---|---|
| MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL | Sí | Integer | Valores: 0, 1, 5, 4, 3 | 
| MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP | Sí | Integer | Valores: 48, 64, 32, 16 | 
| MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3 | Sí | Integer | Valores: 2, 128, 256, 512 | 
| IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES | Sí | Integer | Valores: 3, 2, 5, 7, 1, 4, 6 | 
| StarDesktop | Sí | Objeto | Returns the StarDesktop object that represents the LibreOffice application. | 
| ThisComponent | Sí | Objeto | If the current component refers to a LibreOffice document, this method returns the UNO object representing the document. This property returns None when the current component does not correspond to a document. | 
| ThisDatabaseDocument | Sí | Objeto | If the script is being executed from a Base document or any of its subcomponents this method returns the main component of the Base instance. This property returns None otherwise. | 
Converts a numeric expression or a string to a datetime.datetime Python native object.
This method exposes the Basic builtin function CDate to Python scripts.
svc.CDate(expression: any): obj
expression: a numeric expression or a string representing a date.
    d = bas.CDate(1000.25)
    bas.MsgBox(str(d)) # 1902-09-26 06:00:00
    bas.MsgBox(d.year) # 1902
  Converts a UNO date/time representation to a datetime.datetime Python native object.
svc.CDateFromUnoDateTime(unodate: uno): obj
unodate: A UNO date/time object of one of the following types: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time
El ejemplo siguiente crea un objeto com.sun.star.util.DateTime y lo convierte en un objeto datetime.datetime de Python.
    uno_date = bas.CreateUnoStruct('com.sun.star.util.DateTime')
    uno_date.Year = 1983
    uno_date.Month = 2
    uno_date.Day = 23
    new_date = bas.CDateFromUnoDateTime(uno_date)
    bas.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  Converts a date representation into a com.sun.star.util.DateTime object.
svc.CDateToUnoDateTime(date: obj): uno
date: A Python date/time object of one of the following types: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time.
    from datetime import datetime
    current_datetime = datetime.now()
    uno_date = bas.CDateToUnoDateTime(current_datetime)
    bas.MsgBox(str(uno_date.Year) + "-" + str(uno_date.Month) + "-" + str(uno_date.Day))
  Devuelve la ruta en la notación del sistema correspondiente a un URL file: dado.
svc.ConvertFromUrl(url: str): str
url: un URL file: absoluto.
A system path file name.
    filename = bas.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt")
    bas.MsgBox(filename)
  Devuelve un URL file: para la ruta de sistema dada.
svc.ConvertToUrl(systempath: str): str
systempath: una ruta de nombre de archivo en el formato del sistema, como una cadena.
Un URL file: como cadena.
    url = bas.ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt')
    bas.MsgBox(url)
  Crea una instancia de un servicio de UNO mediante el ProcessServiceManager.
svc.CreateUnoService(servicename: str): uno
servicename: A fully qualified service name such as com.sun.star.ui.dialogs.FilePicker or com.sun.star.sheet.FunctionAccess.
    dsk = bas.CreateUnoService('com.sun.star.frame.Desktop')
  Returns an instance of a UNO structure of the specified type.
svc.CreateUnoStruct(unostructure: str): uno
unostructure: A fully qualified structure name such as com.sun.star.beans.Property or com.sun.star.util.DateTime.
    date_struct = CreateUnoStruct('com.sun.star.util.DateTime')
  Suma una fecha o un lapso de tiempo a una fecha u hora dada un cierto número de veces y devuelve la fecha resultante.
svc.DateAdd(interval: str, number: num, date: datetime): datetime
interval: A string expression from the following table, specifying the date or time interval.
number: A numerical expression specifying how often the interval value will be added when positive or subtracted when negative.
date: A given datetime.datetime value, the interval value will be added number times to this datetime.datetime value.
A datetime.datetime value.
    dt = datetime.datetime(2004, 1, 31)
    dt = bas.DateAdd("m", 1, dt)
    print(dt)
  Returns the number of date or time intervals between two given date/time values.
svc.DateDiff(interval: str, date1: datetime, date2: datetime, firstdayofweek = 1, firstweekofyear = 1): int
interval: A string expression specifying the date interval, as detailed in above DateAdd method.
date1, date2: The two datetime.datetime values to be compared.
Un número.
    date1 = datetime.datetime(2005,1, 1)
    date2 = datetime.datetime(2005,12,31)
    diffDays = bas.DateDiff('d', date1, date2)
    print(diffDays)
  The DatePart function returns a specified part of a date.
svc.DatePart(interval: str, date: datetime, firstdayofweek = 1, firstweekofyear = 1): int
interval: A string expression specifying the date interval, as detailed in above DateAdd method.
date: The date/time from which the result is calculated.
firstdayofweek, firstweekofyear: optional parameters that respectively specify the starting day of a week and the starting week of a year, as detailed in above DateDiff method.
The extracted part for the given date/time.
    print(bas.DatePart("ww", datetime.datetime(2005,12,31)
    print(bas.DatePart('q', datetime.datetime(1999,12,30)
  Calcula un dato de fecha a partir de una cadena de fecha.
svc.DateValue(date: str): datetime
La fecha calculada.
    dt = bas.DateValue("23-02-2011")
    print(dt)
  Convierte un número en una cadena y después le da formato de acuerdo con las especificaciones indicadas.
svc.Format(expression: any, format = ''): str
    txt = bas.Format(6328.2, '##.##0.00')
    print(txt)
  Returns the default context of the process service factory, if existent, else returns a null reference.
GetDefaultContext is an alternative to the getComponentContext() method available from XSCRIPTCONTEXT global variable or from uno.py module.
svc.GetDefaultContext(): uno
The default component context is used, when instantiating services via XMultiServiceFactory. See the Professional UNO chapter in the Developer's Guide on api.libreoffice.org for more information.
    ctx = bas.GetDefaultContext()
  Returns a numerical value that specifies the graphical user interface. This function is only provided for backward compatibility with previous versions.
Refer to system() method from platform Python module to identify the operating system.
svc.GetGuiType(): int
    n = bas.GetGuiType()
  Devuelve el separador de directorios, que depende del sistema operativo, utilizado para especificar las rutas de acceso de los archivos.
Use os.pathsep from os Python module to identify the path separator.
svc.GetPathSeparator(): str
    sep = bas.GetPathSeparator()
  Returns the number of system ticks provided by the operating system. You can use this function to optimize certain processes. Use this method to estimate time in milliseconds:
svc.GetSystemTicks(): int
    ticks_ini = bas.GetSystemTicks()
    time.sleep(1)
    ticks_end = bas.GetSystemTicks()
    bas.MsgBox("{} - {} = {}".format(ticks_end, ticks_ini,ticks_end - ticks_ini))
  Returns the UNO object containing all shared Basic libraries and modules.
This method is the Python equivalent to GlobalScope.BasicLibraries in Basic scripts.
svc.GlobalScope.BasicLibraries(): uno
com.sun.star.script.XLibraryContainer
El ejemplo siguiente carga la biblioteca Gimmicks de BASIC si todavía no se ha cargado.
    libs = bas.GlobalScope.BasicLibraries()
    if not libs.isLibraryLoaded("Gimmicks"):
        libs.loadLibrary("Gimmicks")
  Devuelve el objeto UNO que contiene todas las bibliotecas compartidas de diálogos.
This method is the Python equivalent to GlobalScope.DialogLibraries in Basic scripts.
svc.GlobalScope.DialogLibraries(): uno
com.sun.star.comp.sfx2.DialogLibraryContainer
The following example shows a message box with the names of all available dialog libraries.
    dlg_libs = bas.GlobalScope.DialogLibraries()
    lib_names = dlg_libs.getElementNames()
    bas.MsgBox("\n".join(lib_names))
  svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str
String
    txt = s.InputBox('Introduzca una oración:', "Estimadx usuarix")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")
  For in-depth information please refer to Input/Output to Screen with Python on the Wiki.
Displays a dialog box containing a message and returns an optional value.
MB_xx constants help specify the dialog type, the number and type of buttons to display, plus the icon type. By adding their respective values they form bit patterns, that define the MsgBox dialog appearance.
bas.MsgBox(prompt: str, [buttons: int], [title: str])[: int]
An optional integer as detailed in above IDxx properties.
Returns the current system date and time as a datetime.datetime Python native object.
svc.Now(): datetime
    bas.MsgBox(bas.Now(), bas.MB_OK, "Now")
  Returns an integer color value consisting of red, green, and blue components.
svc.RGB(red:int, green: int, blue: int): int
Integer
    YELLOW = bas.RGB(255,255,0)
  Inspect Uno objects or variables.
svc.Xray(obj: any)
obj: A variable or UNO object.
    bas.Xray(bas.StarDesktop)