Class CalcDoc
- class ooodev.calc.CalcDoc(doc, lo_inst=None)[source]
Bases:
LoInstPropsPartial
,SpreadsheetDocumentComp
,QiPartial
,PropPartial
,GuiPartial
,ServicePartial
,StylePartial
,EventsPartial
,DocIoPartial
[CalcDoc
],CreateDialogPartial
,DispatchPartial
,LibrariesPartial
,DocCommonPartial
,CalcDocPropPartial
,TheDictionaryPartial
,JsonCustomPropsPartial
,PopupRngSelPartial
Defines a Calc Document
- __init__(doc, lo_inst=None)[source]
Constructor
- Parameters:
doc (XSpreadsheetDocument) – UNO object the supports
com.sun.star.sheet.SpreadsheetDocument
service.lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to
None
.
- Raises:
NotSupportedDocumentError – If not a valid Calc document.
- Return type:
None
- activate()
Activates document window.
- Return type:
None
- add_event_document_event_events_disposing(cb)
Adds a listener for an event.
Event is invoked when the broadcaster is about to be disposed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_document_event_occured(cb)
Adds a listener for an event.
Event is invoked when range selection is completed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.document.DocumentEvent
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_document_event_occurred(cb)
Adds a listener for an event.
Event is invoked when range selection is completed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.document.DocumentEvent
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_listener(listener)
Adds an event listener to the component.
- Parameters:
listener (XEventListener) – The event listener to be added.
- Return type:
None
- add_event_modified(cb)
Adds a listener for an event.
Event is invoked when something changes in the object.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_modify_events_disposing(cb)
Adds a listener for an event.
Event is invoked when the broadcaster is about to be disposed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_observers(*args)
Adds observers that gets their
trigger
method called when this classtrigger
method is called.- Parameters:
args (EventObserver) – One or more observers to add.
- Return type:
None
Note
Observers are removed automatically when they are out of scope.
- add_event_print_job_event(cb)
Adds a listener for an event.
Informs the user about the creation or the progress of a PrintJob.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.view.PrintJobEvent
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_print_job_events_disposing(cb)
Adds a listener for an event.
Event is invoked when the broadcaster is about to be disposed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Return type:
None
- Parameters:
cb (Any) –
- add_event_property_change(name, cb)
Adds a listener for an event.
Event is invoked when property is changed.
The callback
EventArgs.event_data
will contain acom.sun.star.beans.PropertyChangeEvent
struct.- Parameters:
name (str) – Property Name
cb (EventArgsCallbackT) – Callback
- Return type:
None
- add_event_property_change_events_disposing(name, cb)
Adds a listener for an event.
Event is invoked when the property listener is about to be disposed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Parameters:
name (str) – Property Name
cb (EventArgsCallbackT) – Callback
- Return type:
None
- add_event_vetoable_change(name, cb)
Adds a listener for an event.
Event is invoked when property is changed.
The callback
EventArgs.event_data
will contain acom.sun.star.beans.PropertyChangeEvent
struct.- Parameters:
name (str) – Property Name
cb (EventArgsCallbackT) – Callback
- Return type:
None
- add_event_vetoable_change_events_disposing(name, cb)
Adds a listener for an event.
Event is invoked when the property listener is about to be disposed.
The callback
EventArgs.event_data
will contain a UNOcom.sun.star.lang.EventObject
struct.- Parameters:
name (str) – Property Name
cb (EventArgsCallbackT) – Callback
- Return type:
None
- add_item_to_toolbar(toolbar_name, item_name, im_fnm)
Add a user-defined icon and command to the start of the specified toolbar.
- Parameters:
toolbar_name (str) – toolbar name.
item_name (str) – item name.
im_fnm (str) – image file path.
- Return type:
None
- apply_styles(*styles, **kwargs)
Applies style to component.
- Parameters:
obj. (styles expandable list of styles object such as Font to apply to) –
kwargs (Any, optional) – Expandable list of key value pairs.
styles (StyleT) –
- Return type:
None
- attach_resource(url, *args)
Informs a model about its resource description.
- Return type:
bool
- Parameters:
url (str) –
args (PropertyValue) –
- call_fun(func_name, *args)[source]
Execute a Calc function by its (English) name and based on the given arguments
- Parameters:
func_name (str) – the English name of the function to execute
args (
Any
) – (Any): the arguments of the called function. Each argument must be either a string, a numeric value or a sequence of sequences ( tuples or list ) combining those types.
- Returns:
- The (string or numeric) value or the array of arrays returned by the call to the function
When the arguments contain arrays, the function is executed as an array function Wrong arguments generate an error
- Return type:
Any
- close(deliver_ownership=True)
Try to close the Document.
Nobody can guarantee real closing of called object - because it can disagree with that if any still running processes can’t be canceled yet. It’s not allowed to block this call till internal operations will be finished here.
- Parameters:
deliver_ownership (bool, optional) – If
True
ownership is delivered to caller. DefaultTrue
.True
delegates the ownership of this closing object to anyone which throw the CloseVetoException. This new owner has to close the closing object again if his still running processes will be finished.False
let the ownership at the original one which called the close() method. They must react for possible CloseVetoExceptions such as when document needs saving and try it again at a later time. This can be useful for a generic UI handling.- Raises:
CancelEventError – If Saving event is canceled.
- Returns:
True
if document was closed; Otherwise,False
.- Return type:
bool
See also
See LibreOffice API: XCloseable.close()
- close_doc()[source]
- close_doc(deliver_ownership: bool)
- close_doc(deliver_ownership=False)
Closes document.
- Parameters:
deliver_ownership (bool, optional) – If
True
ownership is delivered to caller. DefaultTrue
.True
delegates the ownership of this closing object to anyone which throw the CloseVetoException. This new owner has to close the closing object again if his still running processes will be finished.False
let the ownership at the original one which called the close() method. They must react for possible CloseVetoExceptions such as when document needs saving and try it again at a later time. This can be useful for a generic UI handling.- Return type:
None
Note
If
deliver_ownership
isTrue
then new owner has to close the closing object again if his still running processes will be finished.False
let the ownership at the original one which called the close() method. They must react for possible CloseVetoExceptions such as when document needs saving and try it again at a later time. This can be useful for a generic UI handling.Attention
close()
method is called along with any of its events.
- compute_function(fn, cell_range)[source]
Computes a Calc Function
- Parameters:
fn (GeneralFunction | str) – Function to calculate, GeneralFunction Enum value or String such as ‘SUM’ or ‘MAX’
cell_range (XCellRange) – Cell range to apply function on.
- Returns:
result of function if successful. If there is an error then 0.0 is returned.
- Return type:
float
See also
Hint
GeneralFunction
can be imported fromooo.dyn.sheet.general_function
- connect_controller(controller)
Is called whenever a new controller is created for this model.
The com.sun.star.lang.XComponent interface of the controller must be used to recognize when it is deleted.
- Return type:
None
- Parameters:
controller (com.sun.star.frame.XController) –
- create_cell_style(style_name)[source]
Creates a style
- Parameters:
style_name (str) – Style name
- Raises:
Exception – if unable to create style.
- Returns:
Newly created style
- Return type:
XStyle
- create_dialog(x, y, width, height, title)
Creates a dialog.
- Parameters:
x (int) – X coordinate. If
-1
, the dialog Position is not set.y (int) – Y coordinate. If
-1
, the dialog Position is not set.width (int) – Width. If
-1
, the dialog Size is not set.height (int) – Height. If
-1
, the dialog Size is not set.title (str) – Dialog title.
- Returns:
An empty dialog. The dialog contains methods for adding controls.
- Return type:
- classmethod create_doc(loader=None, lo_inst=None, **kwargs)
Creates a new document.
- Parameters:
- Returns:
Class instance representing document.
- Return type:
_T
- classmethod create_doc_from_template(template_path, loader=None, lo_inst=None)
Create a document from a template.
- Parameters:
template_path (PathOrStr) – path to template file.
loader (XComponentLoader, optional) – Component Loader.
lo_inst (LoInst, optional) – Lo instance. Used when created multiple documents.
- Raises:
Exception – If unable to create document.
- Returns:
Class instance representing document.
- Return type:
_T
- classmethod create_macro_doc(loader=None, lo_inst=None)
Create a document that allows executing of macros.
- Parameters:
loader (XComponentLoader) – Component Loader.
lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to None.
- Returns:
Class instance representing document.
- Return type:
_T
Attention
create_doc()
method is called along with any of its events.See also
- disconnect_controller(controller)
is called whenever an existing controller should be deregistered at this model.
The com.sun.star.lang.XComponent interface of the controller must be used to recognize when it is deleted.
- Return type:
None
- Parameters:
controller (com.sun.star.frame.XController) –
- dispatch_cmd(cmd, props=None, frame=None)
Dispatches a LibreOffice command.
- Parameters:
cmd (str) – Command to dispatch such as
GoToCell
. Note: cmd does not contain.uno:
prefix.props (PropertyValue, optional) – properties for dispatch.
frame (XFrame, optional) – Frame to dispatch to.
- Raises:
CancelEventError – If Dispatching is canceled via event.
DispatchError – If any other error occurs.
- Returns:
A possible result of the executed internal dispatch. The information behind this any depends on the dispatch!
- Return type:
Any
- Events:
Note
There are many dispatch command constants that can be found in dispatch Namespace
DISPATCHING
Event args data contains any properties passed in viaprops
.DISPATCHED
Event args data contains any results from the dispatch commands.
- dispose()
Disposes the component.
- Return type:
None
- find_function(func_nm: str) Tuple[PropertyValue] | None [source]
- find_function(idx: int) Tuple[PropertyValue] | None
- find_function(*args, **kwargs)
Finds a function.
- Parameters:
func_nm (str) – function name.
idx (int) – Index of function.
- Returns:
Function properties as tuple on success; Otherwise,
None
.- Return type:
Tuple[PropertyValue, …] | None
- freeze(num_cols, num_rows)[source]
Freezes spreadsheet columns and rows
- Parameters:
num_cols (int) – Number of columns to freeze
num_rows (int) – Number of rows to freeze
- Return type:
None
- freeze_cols(num_cols)[source]
Freezes spreadsheet columns
- Parameters:
num_cols (int) – Number of columns to freeze
- Return type:
None
- freeze_rows(num_rows)[source]
Freezes spreadsheet rows
- Parameters:
num_rows (int) – Number of rows to freeze
- Return type:
None
- classmethod from_current_doc()
Get a document from the current component.
This method is useful in macros where the access to current document is needed. This method does not require the use of the
MacroLoader
in macros.- Parameters:
lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to None.
- Returns:
Class instance representing document.
- Return type:
_T
Example
from ooodev.calc import CalcDoc doc = CalcDoc.from_current_doc() doc.sheets[0]["A1"].Value = "Hello World"
See also
ooodev.utils.lo.Lo.current_doc
- classmethod from_obj(obj, lo_inst=None)[source]
Creates a CalcDoc from an object.
- Parameters:
obj (Any) – Object to create CalcDoc from. Can be a CalcDoc, CalcDocPropPartial, or any object that can be converted to a CalcDoc such as a sheet, cell, or range.
lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to
None
.
- Returns:
CalcDoc if found; Otherwise,
None
- Return type:
New in version 0.46.0.
- get_active_sheet()[source]
Gets the active sheet
- Returns:
Active Sheet if found; Otherwise, None
- Return type:
CalcSheet | None
- get_args()
Provides read access on currently representation of the com.sun.star.document.MediaDescriptor of this model which describes the model and its state
- Return type:
Tuple
[PropertyValue
,...
]
- get_control_access()
Get control access from office document.
- Returns:
control access.
- Return type:
XControlAccess
- get_controller()[source]
Provides access to the controller which currently controls this model
- Raises:
MissingInterfaceError – If unable to access controller
- Returns:
Controller for Spreadsheet Document
- Return type:
XController | None
- get_current_controller()
Provides access to the controller which currently controls this model
- Return type:
XController
- get_current_selection()
Provides read access on current selection on controller
- Return type:
XInterface
- get_custom_properties()
Gets custom properties.
- Returns:
custom properties.
- Return type:
DotDict
Hint
DotDict is a class that allows you to access dictionary keys as attributes or keys. DotDict can be imported from
ooodev.utils.helper.dot_dict.DotDict
.
- get_custom_property(name, default=<object object>)
Gets a custom property.
- Parameters:
name (str) – The name of the property.
default (Any, optional) – The default value to return if the property does not exist.
- Raises:
AttributeError – If the property is not found.
- Returns:
The value of the property.
- Return type:
Any
- classmethod get_doc_from_component(doc, lo_inst=None)
Gets a document.
- Parameters:
doc (XComponent) – Component to build document from.
lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to None.
- Raises:
Exception – If not a valid document.
- Returns:
Document.
- Return type:
_T
- get_dpi()
Gets Dispatch provider interception.
- Returns:
Dispatch provider interception.
- Return type:
XDispatchProviderInterception
- get_frame()
Gets frame from doc.
- Returns:
document frame.
- Return type:
XFrame
- get_frame_comp()
Gets frame from doc as a FrameComp.
- Returns:
document frame.
- Return type:
- get_function_names()[source]
Get a list of all function names.
- Returns:
List of function names if found; Otherwise,
None
.- Return type:
List[str] | None
- get_property(name, default=<object object>)
Get property value
- Parameters:
name (str) – Property Name.
default (Any, optional) – Return value if property value is
None
.
- Returns:
Property value or default.
- Return type:
Any
- get_range_selection_from_popup(title='Please select a range', close_on_mouse_release=False, single_cell_mode=False, initial_value='')
Gets a range selection from a popup that allows the user to select a range with the mouse.
There is a automatic timeout of 60 seconds for the popup to be displayed. The timeout is to prevent the method from hanging indefinitely if the popup is not displayed. If the popup is not displayed within 60 seconds, the method will return
None
.If you are running from the command line, you can use this method; Otherwise, use
invoke_range_selection()
method instead.If macro mode ( no bridge connection ) is detected, the method will use the
invoke_range_selection()
method instead and no result will be returned.- Parameters:
title (str, optional) – The title of the popup. Defaults to “Please select a range”.
close_on_mouse_release (bool, optional) – Specifies if the dialog closes when mouse is released. Defaults to
False
.single_cell_mode (bool, optional) – Specifies if the dialog is in single cell mode. Defaults to
False
.initial_value (str, optional) – The initial value of the range. Defaults to “”.
- Returns:
The range object or
None
if no selection was made.- Return type:
RangeObj | None
Warning
This method requires the GUI to be present and will not work in Headless mode.
Note
- This method triggers the following events when this partial class is used in a class that inherits from EventsPartial:
BeforePopupRangeSelection
AfterPopupRangeSelection
- The event data for the BeforePopupRangeSelection event is a DotDict with the following keys:
doc: The
CalcDoc
objecttitle: The title of the popup
close_on_mouse_release: Specifies if the dialog closes when mouse is released.
single_cell_mode: Specifies if the dialog is in single cell mode.
initial_value: The initial value of the range.
- The event data for the AfterPopupRangeSelection event is a DotDict with the following keys:
view: The
CalcSheetView
objectstate: The state of the selection, either “done” or “aborted”
rng_obj: The
RangeObj
object, which is the range selected by the user orNone
.close_on_mouse_release: Specifies if the dialog closes when mouse is released.
single_cell_mode: Specifies if the dialog is in single cell mode.
initial_value: The initial value of the range selection.
result: The result of the range selection from
RangeSelectionEvent.RangeDescriptor
Can be a string such as$Sheet1.$A$1:$B$2
.
The
GlobalCalcRangeSelector
has the same event data as theAfterPopupRangeSelection
event. See theinvoke_range_selection()
method for an example of using the global event.New in version 0.47.1.
- get_selected_addr()[source]
Gets select cell range addresses
- Raises:
Exception – if unable to get document model
MissingInterfaceError – if unable to get interface XCellRangeAddressable
- Returns:
Cell range addresses.
- Return type:
CellRangeAddress
- get_selected_cell_addr()[source]
Gets the cell address of current selected cell of the active sheet.
- Raises:
CellError – if active selection is not a single cell
- Returns:
Cell Address
- Return type:
CellAddress
Note
CellAddress returns Zero-base values. For instance: Cell
B4
has Column value of1
and Row value of3
- get_selected_range()[source]
Gets select cell range
- Parameters:
doc (XSpreadsheetDocument) – Spreadsheet Document
model (XModel) – model used to access sheet
- Raises:
Exception – if unable to get document model
MissingInterfaceError – if unable to get interface XCellRangeAddressable
- Returns:
Cell range addresses
- Return type:
- get_selection()
Gets selection.
- Returns:
Returns current selection or None.
- Return type:
Any
- get_selection_supplier()
Gets selection supplier
- Returns:
Selection supplier
- Return type:
XSelectionSupplier
- get_services()
Gets service names for the instance.
- Returns:
service names
- Return type:
List[str]
- get_sheet()[source]
- get_sheet(idx: int)
- get_sheet(sheet_name: str)
- get_sheet(*args, **kwargs)
Gets a sheet of spreadsheet document
- Parameters:
idx (int, optional) – Zero based index of spreadsheet. Idx can be a negative value to index from the end of the list. For example, -1 will return the last element.
sheet_name (str, optional) – Name of spreadsheet
- Raises:
MissingNameError – If spreadsheet is not found by name.
IndexError – If spreadsheet is not found by index.
- Returns:
Spreadsheet at index.
- Return type:
- get_sheet_name_from_code_name(code_name)[source]
Gets the sheet name from the code name.
- Parameters:
code_name (str) – Code name of sheet. Case insensitive.
- Returns:
Name of sheet or empty string if not found.
- Return type:
str
Note
The code name may contain any character except for the following:
[]:*?/\
New in version 0.44.1.
- get_sheet_name_from_unique_id(unique_id)[source]
Gets the sheet name from the unique name.
- Parameters:
code_name (str) – Unique name of sheet. Case insensitive.
unique_id (str) –
- Returns:
Name of sheet or empty string if not found.
- Return type:
str
Note
The unique name is a is different then the sheet name and the code name. Unlike the code name the unique name will only contain lower case alpha characters.
New in version 0.44.1.
- get_sheet_names()[source]
Gets names of all existing spreadsheets in the spreadsheet document.
- Returns:
Tuple of sheet names.
- Return type:
Tuple[str, …]
- get_sheets()[source]
Gets all existing spreadsheets in the spreadsheet document.
- Returns:
document sheets
- Return type:
XSpreadsheets
- get_top_window()
Gets top window.
- Returns:
Top window or None if there is no Active Top Window.
- Return type:
XTopWindow | None
- get_url()
Provides information about the location of this model
- Return type:
str
- get_view()[source]
Is the main interface of a SpreadsheetView.
It manages the active sheet within this view.
The
com.sun.star.sheet.SpreadsheetView
service is the spreadsheet’s extension of thecom.sun.star.frame.Controller
service and represents a table editing view for a spreadsheet document.- Returns:
CalcSheetView
- Return type:
mCalcSheetView
- get_view_data()[source]
Gets a set of data that can be used to restore the current view status at later time by using
set_view_data()
- Returns:
View Data
- Return type:
str
- get_view_panes()[source]
represents a pane in a view of a spreadsheet document.
- Parameters:
doc (XSpreadsheetDocument) – Spreadsheet Document
- Raises:
MissingInterfaceError – if unable access the view pane container
- Returns:
List of XViewPane on success; Otherwise, None
- Return type:
List[XViewPane] | None
Note
The com.sun.star.sheet.XViewPane interface’s getFirstVisibleColumn(), getFirstVisibleRow(), setFirstVisibleColumn() and setFirstVisibleRow() methods query and set the start of the exposed area. The getVisibleRange() method returns a com.sun.star.table. CellRangeAddress struct describing which cells are shown in the pane. Columns or rows that are only partly visible at the right or lower edge of the view are not included.
- get_view_states()[source]
Extract the view states for all the sheets from the view data. The states are returned as an array of ViewState objects.
The view data string has the format
100/60/0;0;tw:879;0/4998/0/1/0/218/2/0/0/4988/4998
The view state info starts after the third
;
, the fourth entry. The view state for each sheet is separated by;
Based on a post by user Hanya to: openoffice forum
- Return type:
None
Hint
ViewState
can be imported fromooodev.utils.view_state
- has_controllers_locked()
determines if there is at least one lock remaining.
While there is at least one lock remaining, some notifications for display updates are not broadcasted to the controllers.
- Return type:
bool
- has_custom_property(name)
Gets if a custom property exists.
- Parameters:
name (str) – The name of the property to check.
- Returns:
True
if the property exists, otherwiseFalse
.- Return type:
bool
Make all the toolbars invisible.
- Return type:
None
Hides the main menu bar.
- Return type:
None
- input_box(title, msg, input_value='', ok_lbl='OK', cancel_lbl='Cancel', is_password=False)
Displays an input box and returns the results.
- Parameters:
title (str) – Title for the dialog
msg (str) – Message to display such as “Input your Name”
input_value (str, optional) – Value of input box when first displayed.
ok_lbl (str, optional) – OK button Label. Defaults to “OK”.
cancel_lbl (str, optional) – Cancel Button Label. Defaults to “Cancel”.
is_password (bool, optional) – Determines if the input box is masked for password input. Defaults to
False
.
- Returns:
The value of input or empty string.
- Return type:
str
Note
Raises a global event
GblNamedEvent.INPUT_BOX_CREATING
before creating the dialog. The event args are of typeCancelEventArgs
. Theevent_data
is a dictionary that contains the following key:msg
: The message to display.title
: The title of the dialog.input_value
: The value of the input box when first displayed.ok_lbl
: The label for the OK button.cancel_lbl
: The label for the Cancel button.is_password
: Determines if the input box is masked for password input.frame
: The frame of the dialog. If not set, the frame of the current document is used.
The default
frame
isNone
. If set value must be aXFrame
object.If the event is cancelled, the
result
value ofevent_data` if set will be returned. Otherwise if the event is not handled, a ``CancelEventError
is raised.
- insert_sheet(name: str)[source]
- insert_sheet(name: str, idx: int)
- insert_sheet(name, idx=-1)
Inserts a spreadsheet into document sheet collections.
- Parameters:
name (str) – Name of sheet to insert
idx (int, optional) – zero-based index position of the sheet to insert. Can be a negative value to insert from the end of the collection. Default is
-1
which inserts at the end of the collection.
- Raises:
Exception – If unable to insert spreadsheet
CancelEventError – If SHEET_INSERTING event is canceled
- Returns:
The newly inserted sheet
- Return type:
- Events:
- invoke_range_selection(title='Please select a range', close_on_mouse_release=False, single_cell_mode=False, initial_value='')
Displays a range selection popup that allows the user to select a range with the mouse.
If you are running from the command line, you can use the
get_range_selection_from_popup()
method instead.There is a automatic timeout of 60 seconds for the popup to be displayed. The timeout is to prevent the method from hanging indefinitely if the popup is not displayed. If the popup is not displayed within 60 seconds, the method will return
None
.- Parameters:
title (str, optional) – The title of the popup. Defaults to “Please select a range”.
close_on_mouse_release (bool, optional) – Specifies if the dialog closes when mouse is released. Defaults to
False
.single_cell_mode (bool, optional) – Specifies if the dialog is in single cell mode. Defaults to
False
.initial_value (str, optional) – The initial value of the range. Defaults to “”.
- Return type:
None
Warning
This method requires the GUI to be present and will not work in Headless mode.
Note
- This method triggers the following events when this partial class is used in a class that inherits from EventsPartial:
BeforePopupRangeSelection
AfterPopupRangeSelection
- The event data for the BeforePopupRangeSelection event is a DotDict with the following keys:
doc: The
CalcDoc
objecttitle: The title of the popup
close_on_mouse_release: Specifies if the dialog closes when mouse is released.
single_cell_mode: Specifies if the dialog is in single cell mode.
initial_value: The initial value of the range.
- The event data for the AfterPopupRangeSelection event is a DotDict with the following keys:
view: The
CalcSheetView
objectstate: The state of the selection, either “done” or “aborted”
rng_obj: The
RangeObj
object, which is the range selected by the user orNone
.close_on_mouse_release: Specifies if the dialog closes when mouse is released.
single_cell_mode: Specifies if the dialog is in single cell mode.
initial_value: The initial value of the range selection.
result: The result of the range selection from
RangeSelectionEvent.RangeDescriptor
Can be a string such as$Sheet1.$A$1:$B$2
.
Because popup dialogs can block the main GUI Thread, this method is run in a separate thread. That means it is not possible to return the result of the range selection directly. Instead, the result is passed to the AfterPopupRangeSelection event and in a global event named
GlobalCalcRangeSelector
.The
GlobalCalcRangeSelector
has the same event data as theAfterPopupRangeSelection
event.Example
Example of using the global event
GlobalCalcRangeSelector
. In this caseMyObj
could also be a dialog that need to be update when the range selection is done.from typing import Any from ooodev.globals import GblEvents from ooodev.events.args.event_args import EventArgs class MyObj: def __init__(self): self._fn_on_range_sel = self._on_range_sel GblEvents().subscribe("GlobalCalcRangeSelector", self._fn_on_range_sel) def on_range_selection(self, src:Any, event: EventArgs): if event.event_data.state == "done": print("Range Selection", event.event_data.rng_obj)
New in version 0.47.3.
- lock_controllers()
suspends some notifications to the controllers which are used for display updates.
The calls to XModel.lockControllers() and XModel.unlockControllers() may be nested and even overlapping, but they must be in pairs. While there is at least one lock remaining, some notifications for display updates are not broadcasted.
- Return type:
None
- maximize()
Maximizes document window.
- Return type:
None
- minimize()
Minimizes document window.
- Return type:
None
- move_sheet(name, idx)[source]
Moves a sheet in a spreadsheet document
- Parameters:
name (str) – Name of sheet to move
idx (int) – The zero based index to move sheet into.
- Returns:
True on success; Otherwise, False
- Return type:
bool
- Events:
- msgbox(msg, title='Message', boxtype=MessageBoxType.MESSAGEBOX, buttons=MessageBoxButtonsEnum.BUTTONS_OK)
Simple message box.
- Parameters:
msg (str) – the message for display.
title (str, optional) – the title of the message box. Defaults to “Message”.
boxtype (MessageBoxType, optional) – determines the type of message box to display. Defaults to
Type.MESSAGEBOX
.buttons (MessageBoxButtonsEnum, int, optional) – determines what buttons to display. Defaults to
Buttons.BUTTONS_OK
.
- Returns:
MessageBoxResultsEnum
- Return type:
Results
Note
If BoxType is an integer, the following values are valid:
0:
MESSAGEBOX
1:
INFOBOX
2:
WARNINGBOX
3:
ERRORBOX
4:
QUERYBOX
Note
Button press
Abort
returnMessageBoxResultsEnum.CANCEL
Button press
Cancel
returnMessageBoxResultsEnum.CANCEL
Button press
Ignore
returnsMessageBoxResultsEnum.IGNORE
Button press
No
returnsMessageBoxResultsEnum.NO
Button press
OK
returnsMessageBoxResultsEnum.OK
Button press
Retry
returnsMessageBoxResultsEnum.RETRY
Button press
Yes
returnsMessageBoxResultsEnum.YES
Note
Raises a global event
GblNamedEvent.MSG_BOX_CREATING
before creating the dialog. The event args are of typeCancelEventArgs
. Theevent_data
is a dictionary that contains the following key:msg
: The message to display.title
: The title of the dialog.boxtype
: The type of message box to display.buttons
: The buttons to display.
If the event is cancelled, the
result
value ofevent_data` if set will be returned. Otherwise if the event is not handled, a ``CancelEventError
is raised.
- classmethod open_doc(fnm, loader=None, lo_inst=None, **kwargs)
Open a office document.
- Parameters:
fnm (PathOrStr) – path of document to open.
loader (XComponentLoader, optional) – Component Loader.
lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to None.
visible (bool) – If
True
document is visible; Otherwise, document is invisible. DefaultFalse
.kwargs (Any) –
- Raises:
CancelEventError – if
DOC_OPENING
event is canceled.- Returns:
Class instance representing document.
- Return type:
_T
- Events:
Note
Event args
event_data
is a dictionary containing all method parameters.See also
open_doc()
load_office()
Note
If connection it office is a remote server then File URL must be used, such as
file:///home/user/fancy.odt
- classmethod open_flat_doc(fnm, loader=None, lo_inst=None)
Opens a flat document.
- Parameters:
fnm (PathOrStr) – path of XML document.
loader (XComponentLoader, optional) – Component loader.
lo_inst (LoInst, optional) – Lo instance. Used when created multiple documents.
- Raises:
Exception – if unable to open document.
- Returns:
Class instance representing document.
- Return type:
_T
See also
open_flat_doc()
- classmethod open_readonly_doc(fnm, loader=None, lo_inst=None, **kwargs)
Open a office document as read-only.
- Parameters:
fnm (PathOrStr) – path of document to open.
loader (XComponentLoader) – Component Loader.
lo_inst (LoInst, optional) – Lo instance. Used when created multiple documents.
kwargs (Any) –
- Returns:
Class instance representing document.
- Return type:
_T
See also
- qi(atype, raise_err=False)
Generic method that get an interface instance from an object.
- Parameters:
atype (T) – Interface type to query obj for. Any Uno class that starts with ‘X’ such as XInterface
raise_err (bool, optional) – If True then raises MissingInterfaceError if result is None. Default False
- Raises:
MissingInterfaceError – If ‘raise_err’ is ‘True’ and result is None
- Returns:
instance of interface if supported; Otherwise, None
- Return type:
T | None
Note
When
raise_err=True
return value will never beNone
.
- remove_custom_property(name)
Removes a custom property.
- Parameters:
name (str) – The name of the property to remove.
- Raises:
AttributeError – If the property is a forbidden key.
- Return type:
None
- remove_event_document_event_events_disposing(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_document_event_occured(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_document_event_occurred(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_listener(listener)
Removes an event listener from the component.
- Parameters:
listener (XEventListener) – The event listener to be removed.
- Return type:
None
- remove_event_modified(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_modify_events_disposing(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_observer(observer)
Removes an observer
- Parameters:
observer (EventObserver) – One or more observers to add.
- Returns:
True
if observer has been removed; Otherwise,False
.- Return type:
bool
- remove_event_print_job_event(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_print_job_events_disposing(cb)
Removes a listener for an event
- Return type:
None
- Parameters:
cb (Any) –
- remove_event_property_change(name)
Removes a listener for an event
- Parameters:
name (str) – Property Name
- Return type:
None
- remove_event_property_change_events_disposing(name)
Removes a listener for an event
- Parameters:
name (str) – Property Name
- Return type:
None
- remove_event_vetoable_change(name)
Removes a listener for an event
- Parameters:
name (str) – Property Name
- Return type:
None
- remove_event_vetoable_change_events_disposing(name)
Removes a listener for an event
- Parameters:
name (str) – Property Name
- Return type:
None
- remove_sheet(sheet_name: str)[source]
- remove_sheet(idx: int)
- remove_sheet(*args, **kwargs)
Removes a sheet from document
- Parameters:
sheet_name (str) – Name of sheet to remove
idx (int) – Zero based index of sheet to remove. Can be a negative value to insert from the end of the list.
- Returns:
True of sheet was removed; Otherwise, False
- Return type:
bool
- Events:
Note
Event args
event_data
is set to a dictionary. Ifidx
is available then argsevent_data["fn_type"]
is set to a valueidx
; Otherwise, set to a valuename
.
- save_doc(fnm, password=None, format=None)
Save document.
- Parameters:
fnm (PathOrStr) – file path to save as.
password (str, optional) – password to save document with.
format (str, optional) – document format such as ‘odt’ or ‘xml’.
- Raises:
CancelEventError – If Saving event is canceled.
- Returns:
False
if DOC_SAVING event is canceled; Otherwise,True
- Return type:
bool
- Events:
Note
Event args
event_data
is a dictionary containing all method parameters.Attention
store_doc()
method is called along with any of its events.See also
- set_active_sheet(sheet: com.sun.star.sheet.XSpreadsheet)[source]
- set_active_sheet(sheet: ooodev.calc.calc_sheet.CalcSheet)
- set_active_sheet(sheet)
Sets the active sheet
- Parameters:
sheet (XSpreadsheet) – Sheet to set active
- Events:
- Return type:
None
Note
Event arg properties modified on SHEET_ACTIVATING it is reflected in this method.
- Return type:
None
- Parameters:
sheet (Any) –
- set_current_controller(controller)
sets a registered controller as the current controller.
- Raises:
com.sun.star.container.NoSuchElementException –
NoSuchElementException
- Return type:
None
- Parameters:
controller (com.sun.star.frame.XController) –
- set_custom_properties(properties)
Sets custom properties.
- Parameters:
properties (DotDict) – custom properties to set.
- Return type:
None
Hint
DotDict is a class that allows you to access dictionary keys as attributes or keys. DotDict can be imported from
ooodev.utils.helper.dot_dict.DotDict
.- Return type:
None
- Parameters:
properties (DotDict) –
- set_custom_property(name, value)
Sets a custom property.
- Parameters:
name (str) – The name of the property.
value (Any) – The value of the property.
- Raises:
AttributeError – If the property is a forbidden key.
- set_property(**kwargs)
Set property value
- Parameters:
**kwargs (
Any
) – Variable length Key value pairs used to set properties.- Return type:
None
- set_view_data(view_data)[source]
Restores the view status using the data gotten from a previous call to
get_view_data()
- Parameters:
view_data (str) – Data to restore.
- Return type:
None
- set_view_states(states)[source]
Updates the sheet state part of the view data, which starts as the fourth entry in the view data string.
- Parameters:
states (Sequence[ViewState]) – Sequence of ViewState objects.
- Return type:
None
Hint
ViewState
can be imported fromooodev.utils.view_state
- set_visible()[source]
- set_visible(visible: bool)
- set_visible(visible=True)
Set window visibility.
- Parameters:
visible (bool, optional) – If
True
window is set visible; Otherwise, window is set invisible. DefaultTrue
- Return type:
None
Shows the main menu bar.
- Return type:
None
- split_window(cell_name)[source]
Splits window
- Parameters:
doc (XSpreadsheetDocument) – Spreadsheet Document
cell_name (str) – Cell to preform split on. e.g. ‘C4’
- Return type:
None
- subscribe_event(event_name, callback)
Add an event listener to current instance.
- Parameters:
event_name (str) – Event Name.
callback (EventCallback) – Callback of the event listener.
- Return type:
None
- support_service(*service)
Gets if instance supports a service.
- Parameters:
*service (str) – Variable length argument list of UNO namespace strings such as
com.sun.star.configuration.GroupAccess
- Returns:
True
if instance supports any passed in service; Otherwise,False
- Return type:
bool
- toggle_design_mode()[source]
Toggle Control Design Mode using a dispatch command.
New in version 0.38.0.
- Return type:
Any
Toggles the main menu bar.
- Return type:
None
- trigger_event(event_name, event_args)
Trigger an event on current instance.
- Parameters:
event_name (str) – Event Name.
event_args (EventArgsT) – Event Args.
- Return type:
None
- unlock_controllers()
resumes the notifications which were suspended by XModel.lockControllers().
The calls to XModel.lockControllers() and XModel.unlockControllers() may be nested and even overlapping, but they must be in pairs. While there is at least one lock remaining, some notifications for display updates are not broadcasted.
- Return type:
None
- unsubscribe_event(event_name, callback)
Remove an event listener from current instance.
- Parameters:
event_name (str) – Event Name.
callback (EventCallback) – Callback of the event listener.
- Return type:
None
- zoom(type=ZoomKind.ZOOM_100_PERCENT)[source]
Zooms spreadsheet document to a specific view.
- Parameters:
type (ZoomKind, optional) – Type of Zoom to set. Default is
ZoomKind.ZOOM_100_PERCENT
.- Return type:
None
Hint
ZoomKind
can be imported fromooodev.utils.kind.zoom_kind
- Return type:
None
- Parameters:
type (ZoomKind) –
- zoom_value(value=100)[source]
Sets the zoom level of the Spreadsheet Document
- Parameters:
value (int, optional) – Value to set zoom. e.g. 160 set zoom to 160%. Default is
100
.- Return type:
None
- property basic_libraries: DocumentScriptLibraryContainerComp
Gets the basic libraries container.
- Returns:
The instance.
- Return type:
- property component: com.sun.star.sheet.SpreadsheetDocument
Spreadsheet Document Component
- Return type:
SpreadsheetDocument
- property current_controller: CalcSheetView
Gets the current controller.
- Returns:
Current Controller
- Return type:
- property database_ranges: DatabaseRangesComp
Database Ranges
- Returns:
Database Ranges
- Return type:
New in version 0.45.0.
- property dialog_libraries: DocumentDialogLibraryContainerComp
Gets the dialog libraries container.
- Returns:
The instance.
- Return type:
- property draw_pages: SpreadsheetDrawPages[CalcDoc]
Gets draw pages.
- Returns:
Draw Pages
- Return type:
- property event_observer: EventObserver
Gets/Sets The Event Observer for this instance.
- Return type:
- property events_listener_document_event: DocumentEventListener
Returns listener
- Return type:
- property events_listener_modify: ModifyListener
Returns listener
- Return type:
- property events_listener_print_job: PrintJobListener
Returns listener
- Return type:
- property extra_data: TheDict
Extra Data Key Value Pair Dictionary.
Properties can be assigned properties and access like a dictionary and with dot notation.
Note
This is a dictionary object that can be used to store key value pairs. Generally speaking this data is not part of the object’s main data structure and is not saved with the object (document).
This property is used to store data that is not part of the object’s main data structure and can be used however the developer sees fit.
- Return type:
- property log: NamedLogger
Gets the logger.
- Returns:
The logger.
- Return type:
Gets access to Calc Menus.
- Returns:
Calc Menu
- Return type:
Example
# Example of getting the Calc Menus tools_menu = doc.menu["tools"] tools_menu[3].execute()
New in version 0.40.0.
- property named_ranges: NamedRangesComp
Named Ranges
- Returns:
Named Ranges
- Return type:
NamedRanges
New in version 0.45.0.
- property office_doc: OfficeDocumentT
Office Document.
- Return type:
- property office_document: OfficeDocumentComp
Spreadsheet Document Settings Component
- Return type:
- property python_script: PythonScript
Gets the python script instance.
- Returns:
The instance.
- Return type:
PythonScript
- property range_converter: RangeConverter
Range Converter
- Returns:
Range Converter
- Return type:
- property runtime_uid: str
Gets the runtime id such as 1
- Returns:
The runtime id.
- Return type:
str
- property sheets: CalcSheets
Sheets of Calc Document
- Returns:
Calc Sheets
- Return type:
# example of setting the value of cell A2 to TEST doc.sheets[0]["A2"].set_val("TEST")
New in version 0.17.11.
- property shortcuts: Shortcuts
Gets access to Calc Shortcuts.
- Returns:
Calc Shortcuts
- Return type:
New in version 0.40.0.
- property spreadsheet_document_settings: SpreadsheetDocumentSettingsComp
Spreadsheet Document Settings Component
- Return type:
- property string_value: str
Gets the string value of the doc such as
'vnd.sun.star.tdoc:/1/'
- Returns:
The string value.
- Return type:
str
- property theme: ThemeComp | None
Gets document theme.
- Returns:
Document Theme or
None
if not available.- Return type:
ThemeComp | None
Note
Theme is only supported in LibreOffice
7.6
and later.New in version 0.50.0.
- property version_info: Tuple[int, ...]
Gets the running LibreOffice version.
- Returns:
version as tuple such as
(24, 2, 6, 2)
- Return type:
tuple