Reading and Writing values to Ranges

Macros in LibreOffice Calc often need to read and write values from/to sheets. This help page describes the various approaches to accessing sheets and ranges to read or write their values.

note

All examples presented in this page can be implemented both in Basic and Python.


Acceder a una única celda

The example below enters the numeric value 123 into cell "A1" of the current sheet.


    Dim oSheet as Object
    Dim oCell as Object
    oSheet = ThisComponent.CurrentController.getActiveSheet()
    oCell = oSheet.getCellRangeByName("A1")
    oCell.setValue(123)
  

Se puede lograr lo mismo con Python:


    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.getCurrentController().getActiveSheet()
    cell = sheet.getCellRangeByName("A1")
    cell.setValue(123)
  

Note that in the previous examples the cell is accessed using its range name "A1". It is also possible to access cells using indices as though the sheet were a matrix where columns and rows are indexed starting from zero.

This can be done using the getCellByPosition(colIndex, rowIndex) method, that takes in a column and a row index. The example below in Basic changes the text value in cell "C1" (column 2, row 0).


    oSheet = ThisComponent.CurrentController.getActiveSheet()
    oCell = oSheet.getCellByPosition(2, 0)
    oCell.setString("Hello")
  

El ejemplo también puede implementarse en Python:


    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.getCurrentController().getActiveSheet()
    cell = sheet.getCellByPosition(2, 0)
    cell.setString("Hello")
  
note

The main difference between Python and Basic scripts lies on how to get access to the sheet object by using the XSCRIPTCONTEXT context variable. After that, all methods and properties are identical in Basic and Python.


Valores, cadenas y fórmulas

Las celdas de Calc pueden tener tres tipos de valores: numéricos, de cadena y fórmulas. Cada tipo posee sus propios métodos «get» y «set»:

Tipo

Get Method

Set Method

Numérico

getValue()

setValue(newValue)

Texto

getString()

setString(newString)

Fórmula

getFormula()

setFormula(newFormula)


note

En Calc, las fechas y los valores monetarios se consideran valores numéricos.


The following example enters numeric values into cells "A1" and "A2" and inserts a formula in cell "A3" that returns the multiplication of these values.


    oSheet = ThisComponent.CurrentController.getActiveSheet()
    oCell = oSheet.getCellRangeByName("A1")
    oCell.setValue(10)
    oCell = oSheet.getCellRangeByName("A2")
    oCell.setValue(20)
    oCell = oSheet.getCellRangeByName("A3")
    oCell.setFormula("=A1*A2")
  

Acceder a intervalos de hojas distintas

The previous examples used only the active sheet to perform operations. It is possible to access cell ranges in different sheets by their indices or names.

The example below enters a numeric value into cell "A1" of the sheet named "Sheet2".


    oSheet = ThisComponent.Sheets.getByName("Sheet2")
    oCell = oSheet.getCellRangeByName("A1")
    oCell.setValue(123)
  

El ejemplo también puede implementarse en Python:


    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.Sheets["Sheet2"]
    cell = sheet.getCellRangeByName("A1")
    cell.setValue(123)
  

Sheets can also be accessed using zero-based indices indicating which sheet considering the order they appear in the Calc file.

In Basic, instead of using the getByName method, use Sheets(sheetIndex) as shown next:


    oSheet = ThisComponent.Sheets(0)
  

Esto puede lograrse de manera similar en Python:


    sheet = doc.Sheets[0]
  

Using the ScriptForge Library

Sírvase del servicio Calc de la biblioteca ScriptForge para obtener y establecer valores de celdas:


    

' Carga la biblioteca ScriptForge

GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")

' Obtiene acceso al documento actual de Calc

oDoc = CreateScriptService("Calc")

' Establece los valores de las celdas A1 y A2

oDoc.setValue("A1", "Hello")

oDoc.setValue("A2", 123)

note

The setValue method can be used to set both numeric and text values. To set a cell formula, use the setFormula method.


With the Calc service, getting and setting cell values can be done with a single line of code. The example below gets the value from cell "A1" and shows it on a message box.


    Dim val as Variant, oDoc as Object
    oDoc = CreateScriptService("Calc")
    val = oDoc.getValue("A1")
    MsgBox val
  

La biblioteca ScriptForge también simplifica el acceso a intervalos de distintas hojas, como se demuestra en el ejemplo siguiente:


    Dim val1, val2
    ' Gets cell "A1" from the sheet named "Sheet1"
    val1 = oDoc.getValue("Sheet1.A1")
    ' Gets cell "B3" from the sheet named "Sheet2"
    val2 = oDoc.getValue("Sheet2.B3")
    ' Places the result into cell "A1" of sheet "Report"
    Dim result : result = val1 * val2
    oDoc.setValue("Report.A1", result)
  

Los ejemplos anteriores pueden asimismo implementarse en Python:


    from scriptforge import CreateScriptService
    doc = CreateScriptService("Calc")
    doc.setValue("A1", "Hello")
  

    doc = CreateScriptService("Calc")
    bas = CreateScriptService("Basic")
    val = doc.getValue("A1")
    bas.MsgBox(val)
  

    first_val = doc.getValue("Sheet1.A1")
    second_val = doc.getValue("Sheet2.B3")
    result = first_val * second_val
    doc.setValue("Report.A1", result)