ScriptForge.Basic service

The ScriptForge.Basic service proposes a collection of LibreOffice Basic methods to be executed in a Python context. Basic service methods reproduce the exact syntax and behaviour of Basic builtin functions.

note

This service is available from LibreOffice 7.2 onwards.


Typical example:


   svc.MsgBox('This has to be displayed in a message box')
  
warning

ScriptForge.Basic service is limited to Python scripts.


Service invocation

Before using the Basic service, import the CreateScriptService() method from the scriptforge module:


    from scriptforge import CreateScriptService
    svc = CreateScriptService("Basic")
  

Properties

Name

ReadOnly

Type

Description

MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL

Yes

integer

Values: 0, 1, 5, 4, 3

MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP

Yes

integer

Values: 48, 64, 32, 16

MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3

Yes

integer

Values: 2, 128, 256, 512

IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES

Yes

integer

Values: 3, 2, 5, 7, 1, 4, 6
Constants indicating MsgBox selected button.

StarDesktop

Yes

UNO
object

StarDesktop object represents LibreOffice Start Center.


List of Methods in the Basic Service

CDate
CDateFromUnoDateTime
CDateToUnoDateTime
ConvertFromUrl
ConvertToUrl
CreateUnoService
DateAdd
DateDiff
DatePart

DateValue
Format
GetDefaultContext
GetGuiType
GetPathSeparator
GetSystemTicks
GlobalScope.BasicLibraries
GlobalScope.DialogLibraries
InputBox

MsgBox
Now
RGB
ThisComponent
ThisDatabaseDocument
Xray




CDate

Converts a numeric expression or a string to a datetime.datetime Python native object.

note

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.

When you convert a string expression, the date and time must be entered either in one of the date acceptance patterns defined for your locale setting (see - Language Settings - Languages) or in ISO date format (momentarily, only the ISO format with hyphens, e.g. "2012-12-31" is accepted). In numeric expressions, values to the left of the decimal represent the date, beginning from December 31, 1899. Values to the right of the decimal represent the time.

示例:


    d = svc.CDate(1000.25)
    svc.MsgBox(str(d)) # 1902-09-26 06:00:00
    svc.MsgBox(d.year) # 1902
  

CDateFromUnoDateTime

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

示例:

The following example creates a com.sun.star.util.DateTime object and converts it to a datetime.datetime Python object.


    import uno
    uno_date = uno.createUnoStruct('com.sun.star.util.DateTime')
    uno_date.Year = 1983
    uno_date.Month = 2
    uno_date.Day = 23
    new_date = svc.CDateFromUnoDateTime(uno_date)
    svc.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  

CDateToUnoDateTime

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 = svc.CDateToUnoDateTime(current_datetime)
    svc.MsgBox(str(uno_date.Year) + "-" + str(uno_date.Month) + "-" + str(uno_date.Day))
  

ConvertFromUrl

Returns a system path file name for the given file: URL.

语法:

svc.ConvertFromUrl(url: str): str

参数:

url: An absolute file: URL.

返回值:

A system path file name.

示例:


    filename = svc.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt")
    svc.MsgBox(filename)
  

ConvertToUrl

Returns a file: URL for the given system path.

语法:

svc.ConvertToUrl(systempath: str): str

参数:

systempath: A system file name as a string.

返回值:

A file: URL as a string.

示例:


    url = svc.ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt')
    svc.MsgBox(url)
  

CreateUnoService

Instantiates a UNO service with the 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 = svc.CreateUnoService('com.sun.star.frame.Desktop')
  

DateAdd

Adds a date or time interval to a given date/time a number of times and returns the resulting date.

语法:

svc.DateAdd(interval: str, number: num, date: datetime): datetime

参数:

interval: A string expression from the following table, specifying the date or time interval.

interval (string value)

解释

yyyy

q

季度

m

y

年中某日

w

工作日

ww

年中某周

d

h

小时

n

分钟

s


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 date/time value.

返回值:

A datetime.datetime value.

示例:


    dt = datetime.datetime(2004, 1, 31)
    dt = svc.DateAdd("m", 1, dt)
    print(dt)
  

DateDiff

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.

firstdayofweek: An optional parameter that specifies the starting day of a week.

firstdayofweek value

解释

0

使用系统默认值

1

星期日 (默认)

2

星期一

3

星期二

4

星期三

5

星期四

6

星期五

7

星期六


firstweekofyear: An optional parameter that specifies the starting week of a year.

firstweekofyear value

解释

0

使用系统默认值

1

第 1 周是包含 1 月 1 日的周 (默认)

2

第 1 周是含有当年 4 天以上天数的第 1 周

3

第 1 周是仅包含属于新一年的那几天的第 1 周


返回值:

A number.

示例:


    date1 = datetime.datetime(2005,1, 1)
    date2 = datetime.datetime(2005,12,31)
    diffDays = svc.DateDiff('d', date1, date2)
    print(diffDays)
  

DatePart

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(svc.DatePart("ww", datetime.datetime(2005,12,31)
    print(svc.DatePart('q', datetime.datetime(1999,12,30)
  

DateValue

Computes a date value from a date string.

语法:

svc.DateValue(date: str): datetime

参数:

Date: String expression that contains the date that you want to calculate. In contrast to the DateSerial function that passes years, months and days as separate numeric values, the DateValue function requests the date string to be according to either one of the date acceptance patterns defined for your locale setting (see - Language Settings - Languages) or to ISO date format (momentarily, only the ISO format with hyphens, e.g. "2012-12-31" is accepted).

返回值:

The computed date.

示例:


    dt = svc.DateValue("23-02-2011")
    print(dt)
  

Format

Converts a number to a string, and then formats it according to the format that you specify.

语法:

svc.Format(expression: any, format = ''): str

参数:

expression: Numeric expression that you want to convert to a formatted string.

format: String that specifies the format code for the number. If format is omitted, the Format function works like the LibreOffice Basic Str() function.

返回值:

Text string.

Formatting Codes

The following list describes the codes that you can use for formatting a numeric expression:

0: If expression has a digit at the position of the 0 in the format code, the digit is displayed, otherwise a zero is displayed.

If expression has fewer digits than the number of zeros in the format code, (on either side of the decimal), leading or trailing zeros are displayed. If the expression has more digits to the left of the decimal separator than the amount of zeros in the format code, the additional digits are displayed without formatting.

Decimal places in the expression are rounded according to the number of zeros that appear after the decimal separator in the format code.

#: If expression contains a digit at the position of the # placeholder in the format code, the digit is displayed, otherwise nothing is displayed at this position.

This symbol works like the 0, except that leading or trailing zeroes are not displayed if there are more # characters in the format code than digits in the expression. Only the relevant digits of the expression are displayed.

.」: 小数占位符用于确定小数分隔符左边和右边的位数。

If the format code contains only # placeholders to the left of this symbol, numbers less than 1 begin with a decimal separator. To always display a leading zero with fractional numbers, use 0 as a placeholder for the first digit to the left of the decimal separator.

%: Multiplies the expressionby 100 and inserts the percent sign (%) where the expression appears in the format code.

E- E+ e- e+ : If the format code contains at least one digit placeholder (0 or #) to the right of the symbol E-, E+, e-, or e+, the expression is formatted in the scientific or exponential format. The letter E or e is inserted between the number and the exponent. The number of placeholders for digits to the right of the symbol determines the number of digits in the exponent.

如果指数为负数,则在包含 E-、E+、e- 和 e+ 的指数前显示减号。如果指数为正数,则仅在包含 E+ 或 e+ 的指数前显示加号。

The thousands delimiter is displayed if the format code contains the delimiter enclosed by digit placeholders (0 or #).

句点是否用作千位分隔符和小数分隔符取决于所在的地区设置。当直接在 Basic 源代码中输入数字时,始终使用句点作为小数分隔符。而实际的小数分隔符取决于系统中设置的数字格式。

- + $ ( ) space: A plus (+), minus (-), dollar ($), space, or brackets entered directly in the format code is displayed as a literal character.

要显示此处所列字符以外的字符,则必须在字符前加反斜杠 (\),或在字符前后加引号 (" ")。

\ : The backslash displays the next character in the format code.

Characters in the format code that have a special meaning can only be displayed as literal characters if they are preceded by a backslash. The backslash itself is not displayed, unless you enter a double backslash (\\) in the format code.

在格式代码中,希望显示为文字字符而必须在前面加反斜杠的字符包括日期、时间格式化字符 (a、c、d、h、m、n、p、q、s、t、w、y、/、:) 、数字格式化字符 (#、0、%、E、e、逗号、句点) 和字符串格式化字符 (@、&、<、>、!)。

You can also use the following predefined number formats. Except for "General Number", all of the predefined format codes return the number as a decimal number with two decimal places.

在使用预设格式时,格式名称的前后需要加上引号。

Predefined Formats

General Number」: 显示格式与输入格式相同的数字。

Currency」: 在数字前插入美元符号并在负数前后加上括号。

Fixed」: 小数分隔符前至少显示一位数字。

Standard」: 显示数字时带有千位分隔符。

Percent」: 将数字乘以 100,并附加百分号。

Scientific」:以科学计数法格式显示数字 (例如,1000 显示为 1.00E+03)。

A format code can be divided into three sections that are separated by semicolons. The first part defines the format for positive values, the second part for negative values, and the third part for zero. If you only specify one format code, it applies to all numbers.

您可以在 - 语言设置 - 语言中设置用于控制 LibreOffice Basic 中的数字、日期及货币格式的locale. 在Basic的格式化代码中,总是使用点号 (.) 作为您的locale中定义的小数点符号的「占位符」,并且在实际使用中将会被替换为locale设置中对应的字符。

同样适用于日期、时间和货币格式的区域设置。Basic 格式的代码的解释和显示将遵循您的区域设置。

示例:


    txt = svc.Format(6328.2, '##.##0.00')
    print(txt)
  

GetDefaultContext

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 = svc.GetDefaultContext()
  

GetGuiType

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 = svc.GetGuiType()
  

GetPathSeparator

Returns the operating system-dependent directory separator used to specify file paths.

Use os.pathsep from os Python module to identify the path separator.

语法:

svc.GetPathSeparator(): str


    svc.GetPathSeparator(): str
  

示例:


    sep = svc.GetPathSeparator()
  

GetSystemTicks

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 = svc.GetSystemTicks()
    time.sleep(1)
    ticks_end = svc.GetSystemTicks()
    svc.MsgBox("{} - {} = {}".format(ticks_end, ticks_ini,ticks_end - ticks_ini))
  

GlobalScope.BasicLibraries

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

示例:

The following example loads the Gimmicks Basic library if it has not been loaded yet.


    libs = svc.GlobalScope.BasicLibraries()
    if not libs.isLibraryLoaded("Gimmicks"):
        libs.loadLibrary("Gimmicks")
  

GlobalScope.DialogLibraries

Returns the UNO object containing all shared dialog libraries.

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 = svc.GlobalScope.DialogLibraries()
    lib_names = dlg_libs.getElementNames()
    svc.MsgBox("\n".join(lib_names))
  

InputBox

语法:

svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str

参数:

prompt: String expression displayed as the message in the dialog box.

title: String expression displayed in the title bar of the dialog box.

default: String expression displayed in the text box as default if no other input is given.

xpostwips: Integer expression that specifies the horizontal position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

ypostwips: Integer expression that specifies the vertical position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

If xpostwips and ypostwips are omitted, the dialog is centered on the screen. The position is specified in twips.

返回值:

string

示例:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


MsgBox

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.

语法:

svc.MsgBox(prompt: str, [buttons: int], [title: str])[: int]

参数:

prompt: String expression displayed as a message in the dialog box. Line breaks can be inserted with Chr$(13).

title: String expression displayed in the title bar of the dialog. If omitted, the title bar displays the name of the respective application.

buttons: Any integer expression that specifies the dialog type, as well as the number and type of buttons to display, and the icon type. buttons represents a combination of bit patterns, that is, a combination of elements can be defined by adding their respective values:

返回值:

An optional integer as detailed in above IDxx properties.

示例:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


Now

Returns the current system date and time as a datetime.datetime Python native object.

语法:

svc.Now(): datetime

示例:


    svc.MsgBox(svc.Now(), svc.MB_OK, "Now")
  

RGB

Returns an integer color value consisting of red, green, and blue components.

语法:

svc.RGB(red:int, green: int, blue: int): int

参数:

red: Any integer expression that represents the red component (0-255) of the composite color.

green: Any integer expression that represents the green component (0-255) of the composite color.

blue: Any integer expression that represents the blue component (0-255) of the composite color.

tip

The color picker dialog helps computing red, green and blue components of a composite color. Changing the color of text and selecting Custom color displays the color picker dialog.


返回值:

integer

示例:


    YELLOW = svc.RGB(255,255,0)
  

ThisComponent

If the current component refers to a LibreOffice document, this method returns the UNO object representing the document.

The method will return None when the current component does not correspond to a document.

语法:

svc.ThisComponent(): uno

示例:


    comp = svc.ThisComponent
    svc.MsgBox("\n".join(comp.getSupportedServiceNames()))
  

ThisDatabaseDocument

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 method returns None otherwise.

语法:

svc.ThisDatabaseDocument(): uno

示例:


    db_doc = svc.ThisDatabaseDocument
    table_names = db_doc.DataSource.getTables().getElementNames()
    bas.MsgBox("\n".join(table_names))
  
tip

Visit the OfficeDatabaseDocument API page to learn more about Base's main component structure.


Xray

Inspect Uno objects or variables.

语法:

svc.Xray(obj: any)

参数:

obj: A variable or Uno object.

示例:


    svc.Xray(svc.StarDesktop)
  
warning

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros.


请支持我们!