Usługa SFDocuments.Calc

Biblioteka współdzielona SFDocuments udostępnia szereg metod i właściwości ułatwiających zarządzanie i obsługę dokumentów LibreOffice.

Usługa SFDocuments.Calc jest podklasą usługi SFDocuments.Document. Dostęp do wszystkich metod i właściwości zdefiniowanych dla usługi Document można również uzyskać za pomocą instancji usługi Calc.

Usługa Calc koncentruje się na:

note

Ta strona pomocy opisuje metody i właściwości, które mają zastosowanie tylko do dokumentów programu Calc.


Wywoływanie usługi

Przed użyciem usługi Calc należy załadować lub zaimportować bibliotekę ScriptForge:

note

• Podstawowe makra wymagają załadowania biblioteki ScriptForge przy użyciu następującej instrukcji:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Skrypty Pythona wymagają importu z modułu scriptforge:
from scriptforge import CreateScriptService


Usługa Calc jest ściśle powiązana z usługą UI biblioteki ScriptForge. Poniżej znajduje się kilka przykładów, jak można wywołać usługę Calc.

W języku Basic

Poniższy fragment kodu tworzy instancję usługi Calc odpowiadającą aktualnie aktywnemu dokumentowi Calc.


    Set oDoc = CreateScriptService("Calc")
  

Innym sposobem na utworzenie instancji usługi Calc jest użycie usługi UI. W poniższym przykładzie tworzony jest nowy dokument programu Calc, a oDoc jest instancją usługi Calc:


    Dim ui As Object, oDoc As Object
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.CreateDocument("Calc")
  

Lub używając metody OpenDocument z usługi UI:


    Set oDoc = ui.OpenDocument("C:\Documents\MyFile.ods")
  

Możliwe jest również utworzenie instancji usługi Calc, określając nazwę okna dla metody CreateScriptService:


    Dim oDoc As Object
    Set oDoc = CreateScriptService("SFDocuments.Calc", "MyFile.ods")
  

W powyższym przykładzie „MyFile.ods” to nazwa otwartego okna dokumentu. Jeśli ten argument nie zostanie podany, uwzględniane jest aktywne okno.

Możliwe jest również wywołanie usługi Calc za pomocą dokumentu, do którego odwołuje się ThisComponent. Jest to szczególnie przydatne podczas uruchamiania makr z IDE Basic.


    Dim oDoc As Object
    Set oDoc = CreateScriptService("Calc", ThisComponent)
  

Zaleca się zwolnienie zasobów po użyciu:


    Set oDoc = oDoc.Dispose()
  

Jeśli jednak dokument został zamknięty przy użyciu metody CloseDocument, zwalnianie zasobów za pomocą opisanej powyżej komendy staje się niepotrzebne.

W języku Python

    myDoc = CreateScriptService("Calc")
  

    ui = CreateScriptService("UI")
    myDoc = ui.CreateDocument("Calc")
  

    myDoc = ui.OpenDocument(r"C:\Documents\MyFile.ods")
  

    myDoc = CreateScriptService("SFDocuments.Calc", "MyFile.ods")
    myDoc.Dispose()
  

    bas = CreateScriptService("Basic")
    myDoc = CreateScriptService("Calc", bas.ThisComponent)
  
tip

Użycie prefiksu "SFDocuments." podczas wywoływania usługi jest opcjonalne.


Definicje

Wiele metod wymaga argumentu "Sheet" lub "Range". Pojedyncze komórki są uważane za szczególny przypadek Range.

Obie mogą być wyrażone jako ciąg znaków lub jako odniesienie (= obiekt) w zależności od sytuacji:

Przykład:

Poniższy przykład kopiuje dane z dokumentu A (otwartego tylko do odczytu i ukrytego) do dokumentu B.

W języku Basic

    Dim oDocA As Object, oDocB As Object
    Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
    Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
    oDocB.CopyToRange(oDocA.Range("SheetX.D4:F8"), "D2:F6") 'CopyToRange(source, target)
  
W języku Python

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopyToRange(docA.Range("SheetX.D4:F8"), "D2:F6")
  

SheetName

Albo nazwa arkusza jako string, albo object utworzony przez właściwość .Sheet.

Skrót „~” (tylda) reprezentuje bieżący arkusz.

RangeName

Ciąg określający zestaw ciągłych komórek znajdujących się w arkuszu bieżącej instancji lub object utworzony przez właściwość .Range.

Skrót „~” (tylda) reprezentuje bieżący wybór lub pierwszy wybrany zakres, jeśli wybrano wiele zakresów.

Skrót „*” reprezentuje wszystkie używane komórki.

Nazwa arkusza jest opcjonalna podczas definiowania zakresu. Jeśli nie podano nazwy arkusza, używany jest arkusz aktywny. Otaczające pojedyncze cudzysłowy i znaki $ są dozwolone, ale są ignorowane.

Podczas określania SheetName jako łańcucha, wymagane jest użycie pojedynczych cudzysłowów w celu umieszczenia nazwy arkusza, jeśli nazwa zawiera spacje " " lub kropki ".".

Poniższe przykłady ilustrują, w jakich przypadkach stosowanie pojedynczych cudzysłowów jest obowiązkowe:


      ' Użycie pojedynczych cudzysłowów jest opcjonalne
      oDoc.clearAll("SheetA.A1:B10")
      oDoc.clearAll("'SheetA'.A1:B10")
      ' Użycie pojedynczych cudzysłowów jest wymagane
      oDoc.clearAll("'Sheet.A'.A1:B10")
    
tip

Z wyjątkiem właściwości CurrentSelection, usługa Calc uwzględnia tylko pojedyncze zakresy komórek.


Przykłady prawidłowych zakresów

1) $'SheetX'.D2
2) $D$2

Pojedyncza komórka

1) $'SheetX'.D2:F6
2) D2:D10

Pojedynczy zakres z wieloma komórkami

$'SheetX'.*

Wszystkie użyte komórki w danym arkuszu

1) $'SheetX'.A:A (kolumna A)
2) 3:5 (rzędy 3 do 5)

Wszystkie komórki w ciągłych kolumnach lub wierszach aż do ostatniej użytej komórki

myRange

Zakres o nazwie „myRange” na poziomie arkusza kalkulacyjnego

1) ~.someRange
2) SheetX.someRange

Nazwa zakresu na poziomie arkusza

myDoc.Range("SheetX.D2:F6")

Zakres w arkuszu SheetX w pliku powiązanym z instancją myDoc Calc

~.~ lub ~

Bieżący wybór w aktywnym arkuszu


Właściwości

Wszystkie właściwości ogólne dowolnego dokumentu mają niejawne zastosowanie również do dokumentów programu Calc. Aby uzyskać więcej informacji, przeczytaj stronę pomocy usługi Document.

Właściwości dostępne specjalnie dla dokumentów programu Calc to:

Nazwa

Tylko do odczytu

Argument

Typ zwracany

Opis

CurrentSelection

Nie

Brak

Ciąg lub tablica ciągów

Pojedynczy wybrany zakres jako ciąg znaków lub lista wybranych zakresów jako tablica.

FirstCell

Tak

SheetName lub RangeName jako String

String

Zwraca pierwszą użytą komórkę w danym zakresie lub arkuszu.

FirstColumn

Tak

SheetName lub RangeName jako String

Long

Zwraca numer skrajnej lewej kolumny w danym zakresie lub arkuszu.

FirstRow

Tak

SheetName lub RangeName jako String

Long

Zwraca najwyższy numer wiersza w danym zakresie lub arkuszu.

Height

Tak

RangeName jako String

Long

Liczba wierszy (>= 1) w podanym zakresie.

LastCell

Tak

SheetName lub RangeName jako String

String

Zwraca ostatnio używaną komórkę w danym zakresie lub arkuszu.

LastColumn

Tak

SheetName lub RangeName jako String

Long

Ostatnia używana kolumna w danym zakresie lub arkuszu.

LastRow

Tak

SheetName lub RangeName jako String

Long

Ostatni używany wiersz w danym zakresie lub arkuszu.

Range

Tak

RangeName jako String

Object

Odwołanie do zakresu, którego można użyć jako argumentu metod takich jak CopyToRange.

Region

Tak

RangeName jako String

String

Zwraca adres najmniejszego obszaru zawierającego określony zakres, tak aby obszar ten był otoczony pustymi komórkami lub krawędziami arkusza. Jest to równoważne zastosowaniu skrótu do podanego zakresu.

Sheet

Tak

SheetName jako String

Object

Odwołanie do zakresu, którego można użyć jako argumentu metod takich jak CopySheet.

SheetName

Tak

RangeName jako String

String

Zwraca nazwę arkusza o podanym adresie zakresu.

Sheets

Tak

Brak

Tablica ciągów

Lista z nazwami wszystkich istniejących arkuszy.

Width

Tak

RangeName jako String

Long

Liczba kolumn (>= 1) w podanym zakresie.

XCellRange

Tak

RangeName jako String

Object

Obiekt UNO com.sun.star.Table.XCellRange.

XSheetCellCursor

Tak

RangeName jako String

Object

Obiekt UNO com.sun.star.sheet.XSheetCellCursor. Po przesunięciu kursora uzyskany adres zakresu jest dostępny poprzez właściwość UNO AbsoluteName obiektu kursora, która zwraca wartość ciągu znaków, która może być użyta jako argument dla właściwości i metod usługi Calc.

XSpreadsheet

Tak

SheetName jako String

Object

Obiekt UNO com.sun.star.sheet.XSpreadsheet.


tip

Odwiedź witrynę dokumentacji API LibreOffice, aby dowiedzieć się więcej o obiektach UNO XCellRange, XSheetCellCursor oraz XSpreadsheet.


Metody

Lista metod w usłudze Calc

A1Style
Activate
Charts
ClearAll
ClearFormats
ClearValues
CompactLeft
CompactUp
CopySheet
CopySheetFromFile
CopyToCell
CopyToRange
CreateChart
CreatePivotTable
DAvg

DCount
DMax
DMin
DSum
ExportRangeToFile
Forms
GetColumnName
GetFormula
GetValue
ImportFromCSVFile
ImportFromDatabase
InsertSheet
MoveRange
MoveSheet
Offset

OpenRangeSelector
PrintOut
Printf
RemoveDuplicates
RemoveSheet
RenameSheet
SetArray
SetCellStyle
SetFormula
SetValue
ShiftDown
ShiftLeft
ShiftRight
ShiftUp
SortRange


A1Style

Zwraca adres zakresu jako ciąg na podstawie współrzędnych arkusza, tj. numerów wierszy i kolumn.

Jeśli podano tylko parę współrzędnych, zwracany jest adres do pojedynczej komórki. Dodatkowe argumenty mogą określać prawą dolną komórkę zakresu prostokątnego.

Składnia:

svc.A1Style(row1: int, column1: int, row2: int = 0; column2: int = 0; sheetname: str = "~"): str

Parametry:

row1, column1: określ numery wierszy i kolumn w lewej górnej komórce zakresu, który ma być brany pod uwagę. Numery wierszy i kolumn zaczynają się od 1.

row2, column2: określ numery wierszy i kolumn komórki w prawym dolnym rogu zakresu, który ma być brany pod uwagę. Jeśli te argumenty nie zostaną podane lub podane zostaną wartości mniejsze niż row1 i column1, to adres zakresu pojedynczej komórki reprezentowany przez row1 i column1 jest zwracany.

sheetname: nazwa arkusza, który ma zostać dołączony do zwracanego adresu zakresu. Arkusz musi istnieć. Wartość domyślna to „~” odpowiadająca aktualnie aktywnemu arkuszowi.

Przykład:

Poniższe przykłady w językach Basic i Python uwzględniają, że „Sheet1” jest obecnie aktywnym arkuszem.

W języku Basic

    Set oDoc = CreateScriptService("Calc")
    addr1 = oDoc.A1Style(1, 1) ' '$Sheet1'.$A$1
    addr2 = oDoc.A1Style(2, 2, 3, 6) ' '$Sheet1'.$B$2:$F$3
    addr3 = oDoc.A1Style(2, 2, 0, 6) ' '$Sheet1'.$B$2
    addr4 = oDoc.A1Style(3, 4, 3, 8, "Sheet2") ' '$Sheet2'.$D$3:$H$3
    addr5 = oDoc.A1Style(5, 1, SheetName := "Sheet3") ' '$Sheet3'.$A$5
  
W języku Python

    doc = CreateScriptService("Calc")
    addr1 = doc.A1Style(1, 1) # '$Sheet1'.$A$1
    addr2 = doc.A1Style(2, 2, 3, 6) # '$Sheet1'.$B$2:$F$3
    addr3 = doc.A1Style(2, 2, 0, 6) # '$Sheet1'.$B$2
    addr4 = doc.A1Style(3, 4, 3, 8, "Sheet2") # '$Sheet2'.$D$3:$H$3
    addr5 = doc.A1Style(5, 1, sheetname="Sheet3") # '$Sheet3'.$A$5
  
tip

Metodę A1Style można łączyć z dowolnymi właściwościami i metodami usługi Calc, które wymagają podania zakresu jako argumentu, na przykład GetValue, GetFormula, ClearAll itd.


Activate

Podanie argumentu sheetname powoduje aktywację danego arkusza i staje się aktualnie wybranym arkuszem. W przypadku braku argumentu okno dokumentu jest aktywowane.

Składnia:

svc.Activate(sheetname: str = ""): bool

Parametry:

sheetname: nazwa arkusza, który ma zostać aktywowany w dokumencie. Wartością domyślną jest ciąg pusty, co oznacza, że okno dokumentu zostanie uaktywnione bez zmiany aktywnego arkusza.

Przykład:

Poniższy przykład aktywuje arkusz o nazwie „Sheet4” w aktualnie aktywnym dokumencie.

W języku Basic

    Dim ui as Variant, oDoc as Object
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.GetDocument(ui.ActiveWindow)
    oDoc.Activate("Sheet4")
  
W języku Python

    ui = CreateScriptService("UI")
    myDoc = ui.GetDocument(ui.ActiveWindow)
    myDoc.Activate("Sheet4")
  
tip

Aktywacja arkusza ma znaczenie tylko w dokumentach programu Calc. Aby upewnić się, że pracujesz z dokumentem programu Calc, użyj właściwości isCalc obiektu dokumentu. Ta właściwość zwraca wartość True, jeśli jest to dokument Calcu, w przeciwnym razie zwraca wartość False.


Charts

Zwraca listę z nazwami wszystkich obiektów wykresu w danym arkuszu lub pojedynczą instancję usługi Chart.

Składnia:

svc.Charts(sheetname: str, chartname: str = ""): obj

Parametry:

sheetname: nazwa arkusza, z którego ma zostać pobrana lista wykresów lub w którym znajduje się określony wykres.

chartname: zdefiniowana przez użytkownika nazwa zwracanego obiektu wykresu. Jeżeli wykres nie posiada nazwy zdefiniowanej przez użytkownika, możliwe jest użycie wewnętrznej nazwy obiektu. Jeśli brakuje tego argumentu, zwracana jest lista nazw wykresów na określonym arkuszu.

tip

Użyj paska bocznego Navigator, aby sprawdzić nazwy przypisane do wykresów w kategorii Obiekty OLE.


Przykład:

W języku Basic

Poniższy przykład pokazuje liczbę obiektów wykresu w „Sheet1”.


    Dim arrNames as Object
    arrNames = oDoc.Charts("Sheet1")
    MsgBox "There are " & UBound(arrNames) + 1 & " charts in Sheet1"
  

Poniższy przykład uzyskuje dostęp do wykresu o nazwie „MyChart” w „Sheet1” i drukuje jego typ.


    Dim oChart as Object
    oChart = oDoc.Charts("Sheet1", "MyChart")
    MsgBox oChart.ChartType
  
W języku Python

    bas = CreateScriptService("Basic")
    chart_names = doc.Charts("Sheet1")
    bas.MsgBox(f"There are {len(chart_names)} charts in Sheet1")
  

    chart = doc.Charts("Sheet1", "MyChart")
    bas.MsgBox(chart.ChartType)
  

ClearAll

Czyści całą zawartość i formaty podanego zakresu.

Można określić formułę filtra, aby ustalić, które komórki mają zostać zmienione.

Składnia:

svc.ClearAll(range: str, opt filterformula: str, opt filterscope: str)

Parametry:

range: zakres do wyczyszczenia jako ciąg.

filterformula: formuła Calc, która zostanie zastosowana do podanego zakresu, aby określić, które komórki zostaną naruszone. Określona formuła musi zwracać wartość True lub False. Jeśli ten argument nie zostanie określony, wpłynie to na wszystkie komórki w zakresie.

filterscope: określa, w jaki sposób filterformula jest rozszerzana do podanego zakresu. Ten argument jest obowiązkowy, jeśli podano filterformula. Akceptowane są następujące wartości:

Przykład:

W języku Basic

    ' Czyści wszystkie komórki w zakresie ArkuszX.A1:J10
    oDoc.ClearAll("ArkuszX.A1:J10")
    ' Czyści wszystkie komórki w zakresie ArkuszX.A1:J10, które mają wartość większą niż 100
    oDoc.ClearAll("ArkuszX.A1:J10", "=ArkuszX.A1>100", "CELL")
    ' Czyści wszystkie wiersze w zakresie ArkuszX.A1:J10, których suma jest większa niż 500
    oDoc.ClearAll("ArkuszX.A1:J10", "=SUM(ArkuszX.A1:J1)>100", "ROW")
    ' Czyści wszystkie kolumny w zakresie ArkuszX.A1:J10, których suma jest większa niż 500
    oDoc.ClearAll("ArkuszX.A1:J10", "=SUM(ArkuszX.A1:A10)>100", "COLUMN")
  
W języku Python

    myDoc.ClearAll("ArkuszX.A1:F10")
    myDoc.ClearAll("ArkuszX.A1:J10", "=ArkuszX.A1>100", "CELL")
    myDoc.ClearAll("ArkuszX.A1:J10", "=SUM(ArkuszX.A1:J1)>100", "ROW")
    myDoc.ClearAll("ArkuszX.A1:J10", "=SUM(ArkuszX.A1:A10)>100", "COLUMN")
  

ClearFormats

Czyści formaty i style w podanym zakresie.

Można określić formułę filtra, aby ustalić, które komórki mają zostać zmienione.

Składnia:

svc.ClearFormats(range: str, opt filterformula: str, opt filterscope: str)

Parametry:

range: zakres, którego formaty i style mają zostać wyczyszczone, jako ciąg.

filterformula: formuła Calc, która zostanie zastosowana do podanego zakresu, aby określić, które komórki zostaną naruszone. Określona formuła musi zwracać wartość True lub False. Jeśli ten argument nie zostanie określony, wpłynie to na wszystkie komórki w zakresie.

filterscope: określa, w jaki sposób filterformula jest rozszerzana do podanego zakresu. Ten argument jest obowiązkowy, jeśli podano filterformula. Akceptowane są następujące wartości:

Przykład:

W języku Basic

      oDoc.ClearFormats("SheetX.*")
  
W języku Python

    myDoc.ClearFormats("SheetX.*")
  
tip

Zapoznaj się z dokumentacją metody ClearAll, aby zaznajomić się z przykładami użycia argumentów filterformula i filterscope.


ClearValues

Czyści wartości i formuły w podanym zakresie.

Można określić formułę filtra, aby ustalić, które komórki mają zostać zmienione.

Składnia:

svc.ClearValues(range: str, opt filterformula: str, opt filterscope: str)

Parametry:

range: zakres, którego wartości i formuły mają zostać wyczyszczone, jako ciąg znaków.

filterformula: formuła Calc, która zostanie zastosowana do podanego zakresu, aby określić, które komórki zostaną naruszone. Określona formuła musi zwracać wartość True lub False. Jeśli ten argument nie zostanie określony, wpłynie to na wszystkie komórki w zakresie.

filterscope: określa, w jaki sposób filterformula jest rozszerzana do podanego zakresu. Ten argument jest obowiązkowy, jeśli podano filterformula. Akceptowane są następujące wartości:

Przykład:

W języku Basic

      oDoc.ClearValues("SheetX.A1:F10")
  
W języku Python

    myDoc.ClearValues("SheetX.A1:F10")
  
tip

Zapoznaj się z dokumentacją metody ClearAll, aby zaznajomić się z przykładami użycia argumentów filterformula i filterscope.


CompactLeft

Usuwa kolumny z określonego zakresu, które pasują do filtru wyrażonego jako formuła Calc. Filtr jest stosowany do każdej kolumny, aby zdecydować, czy zostanie ona usunięta, czy nie.

Usuniętą kolumnę można ograniczyć do wysokości podanego zakresu lub rozpiętości do wysokości całego arkusza, usuwając tym samym całe kolumny.

Ta metoda zwraca ciąg z adresem zakresu skompaktowanego zakresu. Jeśli wszystkie kolumny zostaną usunięte, zwracany jest pusty ciąg.

note

Jeśli zaznaczony jest zakres komórek, wywołanie tej metody nie wpłynie na zaznaczenie.


Składnia:

svc.CompactLeft(range: str, wholecolumn: bool = False, opt filterformula: str): str

Parametry:

range: zakres, z którego kolumny zostaną usunięte, jako ciąg.

wholecolumn: jeśli ta opcja jest ustawiona na True, cała kolumna zostanie usunięta z arkusza. Domyślną wartością jest False, co oznacza, że usunięta kolumna będzie ograniczona do wysokości podanego range.

filterformula: filtr, który ma zostać zastosowany do każdej kolumny, aby określić, czy zostanie ona usunięta. Filtr jest wyrażony jako formuła Calc, którą należy zastosować do pierwszej kolumny. Gdy formuła zwróci wartość True dla kolumny, ta kolumna zostanie usunięta. Domyślny filtr usuwa wszystkie puste kolumny.

Załóżmy na przykład, że wybrano zakres A1:J200 (wysokość = 200), więc domyślna formuła to =(LICZ.PUSTE(A1:A200)=200). Oznacza to, że jeśli wszystkie 200 komórek jest pustych w pierwszej kolumnie (Kolumna A), kolumna jest usuwana. Zauważ, że formuła jest wyrażona tylko w odniesieniu do pierwszej kolumny. Wewnętrznie metoda CompactLeft uogólni tę formułę dla wszystkich pozostałych kolumn.

note

Funkcje Calc użyte w argumencie filterformula muszą być wyrażone przy użyciu ich angielskich nazw. Odwiedź stronę Wiki Lista funkcji Calc, aby uzyskać pełną listę funkcji Calc w języku angielskim.


Przykład:

W języku Basic

    ' Usuń wszystkie puste kolumny w zakresie G1:L10 z Sheet1
    newrange = oDoc.CompactLeft("Sheet1.G1:L10")
    ' Poniższy przykład jest podobny, ale cała kolumna jest usuwana z arkusza
    newrange = oDoc.CompactLeft("Sheet1.G1:L10", WholeColumn := True)
    ' Usuwa wszystkie kolumny, w których pierwszy wiersz jest oznaczony znakiem "X"
    newrange = oDoc.CompactLeft("Sheet1.G1:L10", FilterFormula := "=(G1=""X"")")
    ' Usuwa wszystkie kolumny, w których suma wartości w kolumnie jest nieparzysta
    newrange = oDoc.CompactLeft("Sheet1.G1:L10", FilterFormula := "=(MOD(SUM(G1:G10);2)=1)")
  
W języku Python

    newrange = myDoc.CompactLeft("Sheet1.G1:L10")
    newrange = myDoc.CompactLeft("Sheet1.G1:L10", wholecolumn = True)
    newrange = myDoc.CompactLeft("Sheet1.G1:L10", filterformula = '=(G1="X")')
    newrange = myDoc.CompactLeft("Sheet1.G1:L10", filterformula = '=(MOD(SUM(G1:G10);2)=1)')
  

CompactUp

Usuwa wiersze z określonego zakresu, które pasują do filtra wyrażonego jako formuła programu Calc. Filtr jest stosowany do każdego wiersza, aby zdecydować, czy zostanie on usunięty, czy nie.

Usunięte wiersze można ograniczyć do szerokości określonego zakresu lub rozpiętości do szerokości całego arkusza, usuwając tym samym całe wiersze.

Ta metoda zwraca ciąg z adresem zakresu skompaktowanego zakresu. Jeśli wszystkie wiersze zostaną usunięte, zwracany jest pusty ciąg.

note

Jeśli zaznaczony jest zakres komórek, wywołanie tej metody nie wpłynie na zaznaczenie.


Składnia:

svc.CompactUp(range: str, wholerow: bool = False, opt filterformula: str): str

Parametry:

range: zakres, z którego wiersze zostaną usunięte, jako ciąg.

wholerow: Jeśli ta opcja jest ustawiona na True, cały wiersz zostanie usunięty z arkusza. Domyślną wartością jest False, co oznacza, że usuwany wiersz będzie ograniczony do szerokości podanego range.

filterformula: filtr, który ma zostać zastosowany do każdego wiersza, aby określić, czy zostanie on usunięty. Filtr jest wyrażony jako formuła Calc, którą należy zastosować do pierwszego wiersza. Gdy formuła zwróci wartość True dla wiersza, ten wiersz zostanie usunięty. Domyślny filtr usuwa wszystkie puste wiersze.

Załóżmy na przykład, że wybrano zakres A1:J200 (szerokość = 10), więc domyślna formuła to =(LICZ.PUSTE(A1:J1)=10). Oznacza to, że jeśli wszystkie 10 komórek jest pustych w pierwszym wierszu (wiersz 1), wiersz zostanie usunięty. Zauważ, że wzór jest wyrażony tylko w odniesieniu do pierwszego wiersza. Wewnętrznie metoda CompactUp uogólni tę formułę dla wszystkich pozostałych wierszy.

note

Funkcje Calc użyte w formule podanej w argumencie filterformula muszą być wyrażone przy użyciu ich angielskich nazw. Odwiedź stronę Wiki Lista funkcji Calc, aby uzyskać pełną listę funkcji Calc w języku angielskim.


Przykład:

W języku Basic

    ' Usuń wszystkie puste wiersze w zakresie G1:L10 z Sheet1
    newrange = oDoc.CompactUp("Sheet1.G1:L10")
    ' Poniższy przykład jest podobny, ale cały wiersz jest usuwany z arkusza
    newrange = oDoc.CompactUp("Sheet1.G1:L10", WholeRow := True)
    ' Usuwa wszystkie wiersze, w których pierwsza kolumna jest oznaczona znakiem "X"
    newrange = oDoc.CompactUp("Sheet1.G1:L10", FilterFormula := "=(G1=""X"")")
    ' Usuwa wszystkie wiersze, w których suma wartości w wierszu jest nieparzysta
    newrange = oDoc.CompactUp("Sheet1.G1:L10", FilterFormula := "=(MOD(SUM(G1:L1);2)=1)")
  
W języku Python

    newrange = myDoc.CompactUp("Sheet1.G1:L10")
    newrange = myDoc.CompactUp("Sheet1.G1:L10", wholerow = True)
    newrange = myDoc.CompactUp("Sheet1.G1:L10", filterformula = '=(G1="X")')
    newrange = myDoc.CompactUp("Sheet1.G1:L10", filterformula = '=(MOD(SUM(G1:L1);2)=1)')
  

CopySheet

Kopiuje określony arkusz przed istniejącym arkuszem lub na końcu listy arkuszy. Arkusz do skopiowania może znajdować się w dowolnym otwartym dokumencie programu Calc. Zwraca True, jeśli się powiedzie.

Składnia:

svc.CopySheet(sheetname: any, newname: str, [beforesheet: any]): bool

Parametry:

sheetname: nazwa arkusza do skopiowania jako ciąg znaków lub jego odniesienie jako obiekt.

newname: nazwa arkusza do wstawienia. Nazwa nie może być używana w dokumencie.

beforesheet: nazwa (ciąg) lub indeks (liczbowy, począwszy od 1) arkusza, przed którym ma zostać wstawiony skopiowany arkusz. Ten argument jest opcjonalny, a domyślnym zachowaniem jest dodanie skopiowanego arkusza na ostatniej pozycji.

Przykład:

W języku Basic

Poniższy przykład tworzy kopię arkusza „SheetX” i umieszcza go jako ostatni arkusz w bieżącym dokumencie. Nazwa skopiowanego arkusza to „SheetY”.


    Dim oDoc as Object
    'Pobiera obiekt Document aktywnego okna
    Set oDoc = CreateScriptService("Calc")
    oDoc.CopySheet("SheetX", "SheetY")
  

Poniższy przykład kopiuje „SheetX” z „FileA.ods” i wkleja go na ostatniej pozycji „FileB.ods” z nazwą „SheetY”:


      Dim oDocA As Object : Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
      Dim oDocB As Object : Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
      oDocB.CopySheet(oDocA.Sheet("SheetX"), "SheetY")
  
W języku Python

    myDoc.CopySheet("SheetX", "SheetY")
  

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopySheet(docA.Sheet("SheetX"), "SheetY")
  
tip

Aby kopiować arkusze pomiędzy otwartymi dokumentami, użyj CopySheet. Aby skopiować arkusze z dokumentów, które są zamknięte, użyj CopySheetFromFile.


CopySheetFromFile

Kopiuje określony arkusz z zamkniętego dokumentu Calc i wkleja go przed istniejącym arkuszem lub na końcu listy arkuszy pliku, do którego odnosi się obiekt Document.

Jeśli plik nie istnieje, zgłaszany jest błąd. Jeśli plik nie jest prawidłowym plikiem Calc, wstawiany jest pusty arkusz. Jeśli arkusz źródłowy nie istnieje w pliku wejściowym, na górze nowo wklejonego arkusza zostanie wstawiony komunikat o błędzie.

Składnia:

svc.CopySheetFromFile(filename: str, sheetname: str, newname: str, [beforesheet: any]): bool

Parametry:

filename: identyfikuje plik do otwarcia. Musi być zgodny z notacją SF_FileSystem.FileNaming. Plik nie może być chroniony hasłem.

sheetname: nazwa arkusza, który ma zostać skopiowany jako ciąg znaków.

newname: nazwa kopiowanego arkusza, który ma zostać wstawiony do dokumentu. Nazwa nie może być używana w dokumencie.

beforesheet: nazwa (ciąg) lub indeks (liczbowy, począwszy od 1) arkusza, przed którym ma zostać wstawiony skopiowany arkusz. Ten argument jest opcjonalny, a domyślnym zachowaniem jest dodanie skopiowanego arkusza na ostatniej pozycji.

Przykład:

Poniższy przykład kopiuje „SheetX” z „myFile.ods” i wkleja go do dokumentu określanego przez „oDoc” jako „SheetY” na pierwszej pozycji.

W języku Basic

    oDoc.CopySheetFromFile("C:\Documents\myFile.ods", "SheetX", "SheetY", 1)
  
W języku Python

    myDoc.CopySheetFromFile(r"C:\Documents\myFile.ods", "SheetX", "SheetY", 1)
  

CopyToCell

Kopiuje określony zakres źródłowy (wartości, formuły i formaty) do docelowego zakresu lub komórki. Metoda odtwarza zachowanie operacji kopiowania/wklejania z zakresu do pojedynczej komórki.

Zwraca ciąg reprezentujący zmodyfikowany zakres komórek. Rozmiar modyfikowanego obszaru jest w pełni zdeterminowany rozmiarem obszaru źródłowego.

Zakres źródłowy może należeć do innego otwartego dokumentu.

Składnia:

svc.CopyToCell(sourcerange: any, destinationcell: str): str

Parametry:

sourcerange: zakres źródła jako ciąg znaków, jeśli należy do tego samego dokumentu, lub jako odniesienie, jeśli należy do innego otwartego dokumentu programu Calc.

destinationcell: komórka docelowa, do której zostanie wklejony skopiowany zakres komórek w postaci ciągu znaków. Jeśli podany jest zakres, pod uwagę brana jest tylko jego lewa górna komórka.

Przykład:

W języku Basic

Poniżej znajduje się przykład, w którym źródło i miejsce docelowe znajdują się w tym samym pliku:


      oDoc.CopyToCell("SheetX.A1:F10", "SheetY.C5")
  

Poniższy przykład ilustruje, jak skopiować zakres z innego otwartego dokumentu Calc:


    Dim ui as Variant : ui = CreateScriptService("UI")
    Dim oDocSource As Object, oDocDestination As Object
    ' Otwórz dokument źródłowy w tle (ukryty)
    Set oDocSource = ui.OpenDocument("C:\SourceFile.ods", Hidden := True, ReadOnly := True)
    Set oDocDestination = CreateScriptService("Calc")
    oDocDestination.CopyToCell(oDocSource.Range("Sheet1.C2:C4"), "SheetT.A5")
    ' Nie zapomnij zamknąć dokumentu źródłowego, ponieważ został otwarty jako ukryty
    oDocSource.CloseDocument()
  
W języku Python

    docSource = ui.OpenDocument(r"C:\Documents\SourceFile.ods", hidden = True, readonly = True)
    docDestination = CreateScriptService("Calc")
    docDestination.CopyToCell(docSource.Range("Sheet1.C2:C4"), "SheetT.A5")
    docSource.CloseDocument()
  
tip

Aby zasymulować kopiowanie/wklejanie z zakresu do pojedynczej komórki, użyj CopyToCell. Aby zasymulować kopiowanie/wklejanie z zakresu do większego zakresu (przy kilkukrotnej replikacji tych samych komórek), użyj CopyToRange.


CopyToRange

Kopiuje w dół i/lub w prawo określony zakres źródłowy (wartości, formuły i formaty) do zakresu docelowego. Metoda imituje zachowanie operacji kopiowania/wklejania z zakresu źródłowego do większego zakresu docelowego.

Metoda zwraca ciąg znaków reprezentujący zmodyfikowany zakres komórek.

Zakres źródłowy może należeć do innego otwartego dokumentu.

Składnia:

svc.CopyToRange(sourcerange: any, destinationrange: str): str

Parametry:

sourcerange: zakres źródła jako ciąg znaków, jeśli należy do tego samego dokumentu, lub jako odniesienie, jeśli należy do innego otwartego dokumentu programu Calc.

destinationrange: miejsce docelowe skopiowanego zakresu komórek jako ciąg.

Przykład:

W języku Basic

Kopiowanie w ramach jednego dokumentu:


    oDoc.CopyToRange("SheetX.A1:F10", "SheetY.C5:J5")
    ' Zwraca ciąg zakresu: "$SheetY.$C$5:$J$14"
  

Kopiowanie z jednego pliku do drugiego:


    Dim oDocA As Object : Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
    Dim oDocB As Object : Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
    oDocB.CopyToRange(oDocA.Range("SheetX.A1:F10"), "SheetY.C5:J5")
  
W języku Python

    doc.CopyToRange("SheetX.A1:F10", "SheetY.C5:J5")
  

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopyToRange(docA.Range("SheetX.A1:F10"), "SheetY.C5:J5")
  

CreateChart

Tworzy nowy obiekt wykresu przedstawiający dane z określonego zakresu. Zwrócony obiekt wykresu można dalej manipulować za pomocą usługi Chart.

Składnia:

svc.CreateChart(chartname: str, sheetname: str, range: str, columnheader: bool = False, rowheader: bool = False): obj

Parametry:

chartname: zdefiniowana przez użytkownika nazwa wykresu, który ma zostać utworzony. Nazwa musi być unikalna w tym samym arkuszu.

sheetname: nazwa arkusza, w którym zostanie umieszczony wykres.

range: zakres, który ma być używany jako źródło danych dla wykresu. Zakres może odnosić się do dowolnego arkusza dokumentu Calc.

columnheader: gdy True, najwyższy wiersz zakresu jest używany jako etykiety osi kategorii lub legendy (domyślnie = False).

rowheader: gdy True, skrajna lewa kolumna zakresu jest używana jako etykiety osi kategorii lub legendy. (domyślnie = False).

Przykład:

Poniższe przykłady w języku Basic i Python tworzą wykres przy użyciu danych zawartych w zakresie „A1:B5” w „Sheet1” i umieszczają wykres w „Sheet2”.

W języku Basic

    Set oChart = oDoc.CreateChart("MyChart", "Sheet2", "Sheet1.A1:B5", RowHeader := True)
    oChart.ChartType = "Donut"
  
W języku Python

    chart = doc.CreateChart("MyChart", "Sheet2", "Sheet1.A1:B5", rowheader=True)
    chart.ChartType = "Donut"
  
tip

Odwiedź stronę pomocy dotyczącą usługi Chart ScriptForge, aby dowiedzieć się więcej o dalszym manipulowaniu obiektami wykresów. Możliwa jest zmiana właściwości takich jak typ wykresu, tytuł wykresu i osi oraz pozycja wykresu.


CreatePivotTable

Tworzy nową tabelę przestawną z właściwościami zdefiniowanymi przez argumenty przekazane do metody.

Należy podać nazwę tabeli przestawnej. Jeśli w arkuszu docelowym istnieje już tabela przestawna o tej samej nazwie, zostanie ona zastąpiona bez ostrzeżenia.

Ta metoda zwraca ciąg znaków zawierający zakres, w którym została umieszczona nowa tabela przestawna.

Składnia:

svc.CreatePivotTable(pivottablename: str, sourcerange: str, targetcell: str, datafields: str[0..*], rowfields: str[0..*], columnfields: str[0..*], filterbutton: bool = true, rowtotals: bool = true, columntotals: bool = true): str

Parametry:

pivottablename: zdefiniowana przez użytkownika nazwa nowej tabeli przestawnej.

sourcerange: zakres zawierający surowe dane w postaci ciągu znaków. Pierwszy wiersz powinien zawierać nazwy pól, z których korzysta tabela przestawna.

targetcell: lewa górna komórka, w której zostanie umieszczona nowa tabela przestawna. Jeśli określono zakres, uwzględniana jest tylko jego lewa górna komórka.

datafields: może to być pojedynczy ciąg znaków lub tablica zawierająca ciągi znaków definiujące nazwy pól i funkcje, które mają zostać zastosowane. Gdy określono tablicę, musi ona być zgodna ze składnią Array("NazwaPola[;Funkcja]", ...).

Dozwolone funkcje to: Sum, Count, Average, Max, Min, Product, CountNums, StDev, StDevP, Var, VarP i Median. Nazwy funkcji muszą być podawane w języku angielskim. Gdy wszystkie wartości są numeryczne, funkcją domyślną jest Sum. W przeciwnym razie funkcją domyślną jest Count.

rowfields: pojedynczy ciąg znaków lub tablica z nazwami pól, które będą używane jako wiersze tabeli przestawnej.

columnfields: pojedynczy ciąg znaków lub tablica z nazwami pól, które będą używane jako kolumny tabeli przestawnej.

filterbutton: określa, czy przycisk filtru będzie wyświetlany nad tabelą przestawną (domyślnie = True).

rowtotals: określa, czy do tabeli przestawnej zostanie dodana osobna kolumna zawierająca sumy wierszy (domyślnie = True).

columntotals: określa, czy do tabeli przestawnej zostanie dodany oddzielny wiersz zawierający sumy kolumn (domyślnie = True)

Przykład:

W języku Basic

    Dim vData As Variant, oDoc As Object, ui As Object, sTable As String, sPivot As String
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.CreateDocument("Calc")
    vData = Array(Array("Item", "State", "Team", "2002", "2003", "2004"), _
        Array("Books", "Michigan", "Jean", 14788, 30222, 23490), _
        Array("Candy", "Michigan", "Jean", 26388, 15641, 32849), _
        Array("Pens", "Michigan", "Jean", 16569, 32675, 25396), _
        Array("Books", "Michigan", "Volker", 21961, 21242, 29009), _
        Array("Candy", "Michigan", "Volker", 26142, 22407, 32841))
    sTable = oDoc.SetArray("A1", vData)
    sPivot = oDoc.CreatePivotTable("PT1", sTable, "H1", _
        Array("2002", "2003;count", "2004;average"), _ ' Trzy pola danych
        "Item", _ ' A single row field
        Array("State", "Team"), False) ' Two column fields
  
W języku Python

    ui = CreateScriptService("UI")
    doc = ui.CreateDocument("Calc")
    vData = [["Item", "State", "Team", "2002", "2003", "2004"],
             ["Books", "Michigan", "Jean", 14788, 30222, 23490],
             ["Candy", "Michigan", "Jean", 26388, 15641, 32849],
             ["Pens", "Michigan", "Jean", 16569, 32675, 25396)],
             ["Books", "Michigan", "Volker", 21961, 21242, 29009],
             ["Candy", "Michigan", "Volker", 26142, 22407, 32841]]
    sTable = doc.SetArray("A1", vData)
    sPivot = doc.CreatePivotTable("PT1", sTable, "H1",
                                  ["2002", "2003;count", "2004;average"],
                                  "Item",
                                  ["State", "Team"], False)
  
tip

To learn more about Pivot Tables in LibreOffice Calc, read the Pivot Table help page.


DAvg, DCount, DMax, DMin and DSum

Apply the functions Average, Count, Max, Min and Sum, respectively, to all the cells containing numeric values on a given range, excluding values from filtered and hidden rows and hidden columns, the same as for the status bar functions.

Składnia:

svc.DAvg(range: str): float

svc.DCount(range: str): float

svc.DMax(range: str): float

svc.DMin(range: str): float

svc.DSum(range: str): float

Parametry:

range: The range to which the function will be applied, as a string.

Przykład:

The example below applies the Sum function to the range "A1:A1000" of the currently selected sheet:

W języku Basic

      result = oDoc.DSum("~.A1:A1000")
  
W języku Python

    result = myDoc.DSum("~.A1:A1000")
  
note

Cells in the given range that contain text will be ignored by all of these functions. For example, the DCount method will not count cells with text, only numerical cells.


ExportRangeToFile

Exports the specified range as an image or PDF file.

This method returns True if the destination file was successfully saved.

note

Hidden rows or columns in the specified range are not exported to the destination file.


Składnia:

svc.ExportRangeToFile(range: str, filename: str, imagetype: str = "pdf", overwrite: bool = False): bool

Parametry:

range: A sheet name or a cell range to be exported, as a string.

filename: The name of the file to be saved. It must follow the SF_FileSystem.FileNaming notation.

imagetype: Identifies the destination file type. Possible values are "jpeg", "pdf" (default) and "png".

overwrite: When set to True, the destination file may be overwritten (Default = False).

Przykład:

W języku Basic

    ' Exports the entire sheet as a PDF file
    oDoc.ExportRangeToFile("SheetX", "C:\Temp\image.pdf")
    ' Exports the range as a PNG file and overwrites the destination file if it exists
    oDoc.ExportRangeToFile("SheetX.A1:D10", "C:\Temp\image.png", "png", Overwrite := True)
  
W języku Python

    doc.ExportRangeToFile("SheetX", r"C:\Temp\image.pdf")
    doc.ExportRangeToFile("SheetX.A1:D10", r"C:\Temp\image.png", "png", overwrite = True)
  

Forms

Depending on the parameters provided this method will return:

Składnia:

svc.Forms(sheetname: str): str[0..*]

svc.Forms(sheetname: str, form: str = ''): svc

svc.Forms(sheetname: str, form: int): svc

Parametry:

sheetname: The name of the sheet, as a string, from which the form will be retrieved.

form: The name or index corresponding to a form stored in the specified sheet. If this argument is absent, the method will return a list with the names of all forms available in the sheet.

Przykład:

In the following examples, the first line gets the names of all forms stored in "Sheet1" and the second line retrieves the Form object of the form named "Form_A" which is stored in "Sheet1".

W języku Basic

    Set FormNames = oDoc.Forms("Sheet1")
    Set FormA = oDoc.Forms("Sheet1", "Form_A")
  
W języku Python

    form_names = doc.Forms("Sheet1")
    form_A = doc.Forms("Sheet1", "Form_A")
  

GetColumnName

Converts a column number ranging between 1 and 1024 into its corresponding letter (column 'A', 'B', ..., 'AMJ'). If the given column number is outside the allowed range, a zero-length string is returned.

Składnia:

svc.GetColumnName(columnnumber: int): str

Parametry:

columnnumber: The column number as an integer value in the interval 1 ... 1024.

Przykład:

W języku Basic

Displays a message box with the name of the third column, which by default is "C".


    MsgBox oDoc.GetColumnName(3)
  
W języku Python

    bas = CreateScriptService("Basic")
    bas.MsgBox(myDoc.GetColumnName(3))
  
note

The maximum number of columns allowed on a Calc sheet is 1024.


GetFormula

Get the formula(s) stored in the given range of cells as a single string, a 1D or a 2D array of strings.

note

The names of Calc functions used in the returned formulas are expressed in English. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


Składnia:

svc.GetFormula(range: str): any

Parametry:

range: The range where to get the formulas from, as a string.

Przykład:

W języku Basic

The following example returns a 3 by 2 array with the formulas in the range "A1:B3" (3 rows by 2 columns):


    arrFormula = oDoc.GetFormula("~.A1:B3")
  
W języku Python

    arrFormula = myDoc.GetFormula("~.A1:B3")
  

GetValue

Get the value(s) stored in the given range of cells as a single value, a 1D array or a 2D array. All values are either doubles or strings.

Składnia:

svc.GetValue(range: str): any

Parametry:

range: The range where to get the values from, as a string.

Przykład:

W języku Basic

      arrValues = oDoc.GetValue("~.B1:C100")
  
W języku Python

    arrValues = myDoc.GetValue("~.B1:C100")
  
note

If a cell contains a date, the number corresponding to that date will be returned. To convert numeric values to dates in Basic scripts, use the Basic CDate builtin function. In Python scripts, use the CDate function from the Basic service.


ImportFromCSVFile

Imports the contents of a CSV-formatted text file and places it on a given destination cell.

The destination area is cleared of all contents and formats before inserting the contents of the CSV file. The size of the modified area is fully determined by the contents of the input file.

The method returns a string representing the modified range of cells.

Składnia:

svc.ImportFromCSVFile(filename: str, destinationcell: str, [filteroptions: str]): str

Parametry:

filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation.

destinationcell: The destination cell to insert the imported data, as a string. If instead a range is given, only its top-left cell is considered.

filteroptions: The arguments for the CSV input filter. The default filter makes following assumptions:

Przykład:

W języku Basic

    oDoc.ImportFromCSVFile("C:\Temp\myCSVFile.csv", "SheetY.C5")
  
W języku Python

    myDoc.ImportFromCSVFile(r"C:\Temp\myCSVFile.csv", "SheetY.C5")
  
tip

To learn more about the CSV Filter Options, refer to the CSV Filter Options help page.


ImportFromDatabase

Imports the contents of a database table, query or resultset, i.e. the result of a SELECT SQL command, inserting it on a destination cell.

The destination area is cleared of all contents and formats before inserting the imported contents. The size of the modified area is fully determined by the contents in the table or query.

The method returns True when the import was successful.

Składnia:

svc.ImportFromDatabase(filename: str = "", registrationname: str = "", destinationcell: str = "", sqlcommand: str = "", directsql: bool): bool

Parametry:

filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation.

registrationname: The name to use to find the database in the databases register. This argument is ignored if a filename is provided.

destinationcell: The destination of the imported data, as a string. If a range is given, only its top-left cell is considered.

sqlcommand: A table or query name (without surrounding quotes or square brackets) or a SELECT SQL statement in which table and field names may be surrounded by square brackets or quotes to improve its readability.

directsql: When True, the SQL command is sent to the database engine without pre-analysis. Default is False. The argument is ignored for tables. For queries, the applied option is the one set when the query was defined.

Przykład:

W języku Basic

    oDoc.ImportFromDatabase("C:\Temp\myDbFile.odb", , "SheetY.C5", "SELECT * FROM [Employees] ORDER BY [LastName]")
  
W języku Python

    myDoc.ImportFromDatabase(r"C:\Temp\myDbFile.odb", , "SheetY.C5", "SELECT * FROM [Employees] ORDER BY [LastName]")
  

InsertSheet

Inserts a new empty sheet before an existing sheet or at the end of the list of sheets.

Składnia:

svc.InsertSheet(sheetname: str, [beforesheet: any]): bool

Parametry:

sheetname: The name of the new sheet.

beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which to insert the new sheet. This argument is optional and the default behavior is to insert the sheet at the last position.

Przykład:

The following example inserts a new empty sheet named "SheetX" and places it before "SheetY":

W języku Basic

    oDoc.InsertSheet("SheetX", "SheetY")
  
W języku Python

    myDoc.InsertSheet("SheetX", "SheetY")
  

MoveRange

Moves a specified source range to a destination range of cells. The method returns a string representing the modified range of cells. The dimension of the modified area is fully determined by the size of the source area.

Składnia:

svc.MoveRange(source: str, destination: str): str

Parametry:

source: The source range of cells, as a string.

destination: The destination cell, as a string. If a range is given, its top-left cell is considered as the destination.

Przykład:

W języku Basic

    oDoc.MoveRange("SheetX.A1:F10", "SheetY.C5")
  
W języku Python

    myDoc.MoveRange("SheetX.A1:F10", "SheetY.C5")
  

MoveSheet

Moves an existing sheet and places it before a specified sheet or at the end of the list of sheets.

Składnia:

svc.MoveSheet(sheetname: str, [beforesheet: any]): bool

Parametry:

sheetname: The name of the sheet to move. The sheet must exist or an exception is raised.

beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which the original sheet will be placed. This argument is optional and the default behavior is to move the sheet to the last position.

Przykład:

The example below moves the existing sheet "SheetX" and places it before "SheetY":

W języku Basic

    oDoc.MoveSheet("SheetX", "SheetY")
  
W języku Python

    myDoc.MoveSheet("SheetX", "SheetY")
  

Offset

Returns a new range (as a string) offset by a certain number of rows and columns from a given range.

This method has the same behavior as the homonymous Calc's Offset function.

Składnia:

svc.Offset(reference: str, rows: int = 0, columns: int = 0, [height: int], [width: int]): str

Parametry:

reference: The range, as a string, that the method will use as reference to perform the offset operation.

rows: The number of rows by which the initial range is offset upwards (negative value) or downwards (positive value). Use 0 (default) to stay in the same row.

columns: The number of columns by which the initial range is offset to the left (negative value) or to the right (positive value). Use 0 (default) to stay in the same column.

height: The vertical height for an area that starts at the new range position. Omit this argument when no vertical resizing is needed.

width: The horizontal width for an area that starts at the new range position. Omit this argument when no horizontal resizing is needed.

Arguments rows and columns must not lead to zero or negative start row or column.

Arguments height and width must not lead to zero or negative count of rows or columns.

Przykład:

W języku Basic

    oDoc.Offset("A1", 2, 2)
    'SheetX.$C$3 (A1 moved by two rows and two columns down)
    oDoc.Offset("A1", 2, 2, 5, 6)
    'SheetX.$C$3:$H$7 (A1 offset by two rows and columns with width of 5 rows and 6 columns)
  
W języku Python

    myDoc.Offset("A1", 2, 2)
    myDoc.Offset("A1", 2, 2, 5, 6)
  

OpenRangeSelector

Opens a non-modal dialog that can be used to select a range in the document and returns a string containing the selected range.

note

This method opens the same dialog that is used by LibreOffice when the Shrink button is pressed. For example, the Tools - Goal Seek dialog has a Shrink button to the right of the Formula cell field.


This method does not change the current selection.

Składnia:

svc.OpenRangeSelector(opt title: str, opt selection: str, singlecell: bool = False, closeafterselect: bool = True): str

Parametry:

title: The title of the dialog, as a string.

selection: An optional range that is initially selected when the dialog is displayed.

singlecell: When True (default) only single-cell selection is allowed. When False range selection is allowed.

closeafterselect: When True (default) the dialog is closed immediately after the selection is made. When False the user can change the selection as many times as needed and then manually close the dialog.

Przykład:

W języku Basic

    Dim sRange as String
    sRange = oDoc.OpenRangeSelector(Title := "Select a range")
  
W języku Python

    sRange = myDoc.OpenRangeSelector(title = "Select a range")
  

Printf

Returns the input string after substituting its token characters by their values in a given range.

This method does not change the current selection.

tip

This method can be used to quickly extract specific parts of a range name, such as the sheet name or first cell column and row, and use them to compose a new range address.


Składnia:

svc.Printf(inputstr: str, range: str, tokencharacter: str = "%"): str

Parametry:

inputstr: The string containing the tokens that will be replaced by the corresponding values in range.

range: A RangeName from which values will be extracted. If it contains a sheet name, the sheet must exist.

tokencharacter: Character used to identify tokens. By default "%" is the token character. The following tokens are accepted:

Przykład:

W języku Basic

The example below extracts each element of the RangeName defined in sRange and uses them to compose a message.


    Dim sRange as String, sInputStr as String
    sRange = "Sheet1.A1:E10"
    sInputStr = "Sheet name: %S" & Chr(10) & _
                "First row: %R1" & Chr(10) & _
                "First column %C1" & Chr(10) & _
                "Last row %R2" & Chr(10) & _
                "Last column %C2"
    MsgBox oDoc.Printf(sInputStr, sRange)
  

The Printf method can be combined with SetFormula to create formulas over multiple cells. For instance, consider a table with numeric values in the range "A1:E10" from which formulas are to be created to sum the values in each row and place the results in the range "F1:F10":


    Dim sFormula as String, sRange as String
    sRange = "A1:E10"
    ' Note the use of the "$" character
    sFormula = "=SUM($%C1%R1:$%C2%R1)"
    oDoc.SetFormula("F1:F10", oDoc.Printf(sFormula, sRange))
  
W języku Python

    sRange = "Sheet1.A1:E10"
    sInputStr = "Sheet name: %S\n" \
                "First row: %R1\n" \
                "First column %C1\n" \
                "Last row %R2\n" \
                "Last column %C2"
    bas = CreateScriptService("Basic")
    bas.MsgBox(myDoc.Printf(sInputStr, sRange))
  

    sRange = "A1:E10
    sFormula = "=SUM($%C1%R1:$%C2%R1)"
    myDoc.SetFormula("F1:F10", myDoc.Printf(sFormula, sRange))
  

PrintOut

This method sends the contents of the given sheet to the default printer or to the printer defined by the SetPrinter method of the Document service.

Returns True if the sheet was successfully printed.

Składnia:

svc.PrintOut(opt sheetname: str, pages: str = "", copies: num = 1): bool

Parametry:

sheetname: The sheet to print, default is the active sheet.

pages: The pages to print as a string, like in the user interface. Example: "1-4;10;15-18". Default is all pages.

copies: The number of copies. Default is 1.

Przykład:

W języku Basic

    If oDoc.PrintOut("SheetX", "1-4;10;15-18", Copies := 2) Then
        ' ...
    End If
  
W języku Python

    if doc.PrintOut('SheetX', copies=3, pages='45-88'):
        # ...
  

RemoveDuplicates

Removes duplicate rows from a specified range. The comparison to determine if a given row is a duplicate is done based on a subset of columns in the range.

This method returns a string containing the resulting range.

note

The removal of duplicate rows is done starting at the first row in the range moving downwards, meaning that if two or more rows are duplicates then only the first one is kept.


Składnia:

svc.RemoveDuplicates(range: str, opt columns: int[0..*], header: bool = False, casesensitive: bool = False, mode: str = "COMPACT"): str

Parametry:

range: The range from which duplicates will be removed, as a string.

columns: An array containing column numbers indicating which columns will be considered to determine if a row is a duplicate or not. If this argument is left blank, then only the first column is used. Items in this array must be in the interval between 1 and the range width.

header: Specifies whether the first row is a header row (Default = False).

casesensitive: Specifies whether string comparisons are case-sensitive (Default = False).

mode: Specifies what to do with duplicate rows. If mode = "CLEAR" then duplicates are simply removed from the sheet leaving the cells blank. If mode = "COMPACT" then duplicates are removed and empty rows are compacted up (Default = "COMPACT").

Przykład:

W języku Basic

    ' Removes duplicate rows where values in column A are duplicate
    ' Note that all optional arguments use their default value
    oDoc.RemoveDuplicates("A1:B10")
    ' Removes duplicate rows considering that the first row contains headers
    ' Columns A and B are used to determine if a row is a duplicate
    ' Cells containing duplicate values are left blank
    oDoc.RemoveDuplicates("A1:D10", columns := Array(1, 2), header := True, mode := "CLEAR")
  
W języku Python

    myDoc.RemoveDuplicates("A1:B10")
    myDoc.RemoveDuplicates("A1:D10", columns = (1, 2), header = True, mode = "CLEAR")
  

RemoveSheet

Removes an existing sheet from the document.

Składnia:

svc.RemoveSheet(sheetname: str): bool

Parametry:

sheetname: The name of the sheet to remove.

Przykład:

W języku Basic

    oDoc.RemoveSheet("SheetY")
  
W języku Python

    myDoc.RemoveSheet("SheetY")
  

RenameSheet

Renames the given sheet and returns True if successful.

Składnia:

svc.RenameSheet(sheetname: str, newname: str): bool

Parametry:

sheetname: The name of the sheet to rename.

newname: the new name of the sheet. It must not exist yet.

Przykład:

This example renames the active sheet to "SheetY":

W języku Basic

    oDoc.RenameSheet("~", "SheetY")
  
W języku Python

    mydoc.RenameSheet("~", "SheetY")
  

SetArray

Stores the given value starting from a specified target cell. The updated area expands itself from the target cell or from the top-left corner of the given range to accommodate the size of the input value argument. Vectors are always expanded vertically.

The method returns a string representing the modified area as a range of cells.

Składnia:

svc.SetArray(targetcell: str, value: any): str

Parametry:

targetcell: The cell or a range as a string from where to start to store the given value.

value: A scalar, a vector or an array (in Python, one or two-dimensional lists and tuples) with the new values to be stored from the target cell or from the top-left corner of the range if targetcell is a range. The new values must be strings, numeric values or dates. Other types will cause the corresponding cells to be emptied.

Przykład:

W języku Basic

The following example uses the builtin DimArray function to create an array and then store it in cell "A1":


    Dim arrData as Variant
    arrData = DimArray(2, 1)
    arrData(0, 0) = 1 : arrData(1, 0) = 2 : arrData(2, 0) = 3
    arrData(0, 1) = "One" : arrData(1, 1) = "Two" : arrData(2, 1) = "Three"
    oDoc.SetArray("Sheet1.A1", arrData)
  

This example uses the RangeInit method of the ScriptForge Array service to create an array with values that are then stored from cell "A1" and downwards.


    'Fill 1st column with values from 1 to 1000
    oDoc.SetArray("Sheet1.A1", SF_Array.RangeInit(1, 1000))
  
W języku Python

    arrData = ((1, "One"), (2, "Two"), (3, "Three"))
    myDoc.SetArray("Sheet1.A1", arrData)
  

    myDoc.SetArray("Sheet1.A1", tuple(i + 1 for i in range(1000)))
  
tip

To dump the full contents of an array in a sheet, use SetArray. To dump the contents of an array only within the boundaries of the targeted range of cells, use SetValue.


SetCellStyle

Applies the specified cell style to the given target range. The full range is updated and the remainder of the sheet is left untouched. If the cell style does not exist, an error is raised.

The method returns a string representing the modified area as a range of cells.

Składnia:

svc.SetCellStyle(targetrange: str, style: str, opt filterformula: str, opt filterscope: str): str

Parametry:

targetrange: The range to which the style will be applied, as a string.

style: The name of the cell style to apply.

filterformula: formuła Calc, która zostanie zastosowana do podanego zakresu, aby określić, które komórki zostaną naruszone. Określona formuła musi zwracać wartość True lub False. Jeśli ten argument nie zostanie określony, wpłynie to na wszystkie komórki w zakresie.

filterscope: określa, w jaki sposób filterformula jest rozszerzana do podanego zakresu. Ten argument jest obowiązkowy, jeśli podano filterformula. Akceptowane są następujące wartości:

Przykład:

W języku Basic

    oDoc.SetCellStyle("A1:J1", "Heading 1")
    oDoc.SetCellStyle("A2:J100", "Neutral")
  
W języku Python

    myDoc.SetCellStyle("A1:J1", "Heading 1")
    myDoc.SetCellStyle("A2:J100", "Neutral")
  
tip

Refer to the ClearAll method documentation for examples on how to use the arguments filterformula and filterscope.


SetFormula

Inserts the given (array of) formula(s) in the specified range. The size of the modified area is equal to the size of the range.

The method returns a string representing the modified area as a range of cells.

Składnia:

svc.SetFormula(targetrange: str, formula: any): str

Parametry:

targetrange: The range to insert the formulas, as a string.

formula: A string, a vector or an array of strings with the new formulas for each cell in the target range.

The full range is updated and the remainder of the sheet is left unchanged.

If the given formula is a string, the unique formula is pasted along the whole range with adjustment of the relative references.

If the size of formula is smaller than the size of targetrange, then the remaining cells are emptied.

If the size of formula is larger than the size of targetrange, then the formulas are only partially copied until it fills the size of targetrange.

Vectors are always expanded vertically, except if targetrange has a height of exactly 1 row.

note

Calc functions used in the formula argument must be expressed using their English names. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


Przykład:

W języku Basic

    oDoc.SetFormula("A1", "=A2")
    'Horizontal vector, partially empty
    oDoc.SetFormula("A1:F1", Array("=A2", "=B2", "=C2+10"))
    'D2 contains the formula "=H2"
    oDoc.SetFormula("A1:D2", "=E1")
  
W języku Python

    myDoc.SetFormula("A1", "=A2")
    myDoc.SetFormula("A1:F1", ("=A2", "=B2", "=C2+10"))
    myDoc.SetFormula("A1:D2", "=E1")
  

SetValue

Stores the given value in the specified range. The size of the modified area is equal to the size of the target range.

The method returns a string representing the modified area as a range of cells.

Składnia:

svc.SetValue(targetrange: str, value: any): str

Parametry:

targetrange: The range where to store the given value, as a string.

value: A scalar, a vector or an array with the new values for each cell of the range. The new values must be strings, numeric values or dates. Other types will cause the corresponding cells to be emptied.

The full range is updated and the remainder of the sheet is left unchanged. If the size of value is smaller than the size of targetrange, then the remaining cells will be emptied.

If the size of value is larger than the size of targetrange, then value is only partially copied until it fills the size of targetrange.

Vectors are expanded vertically, except if targetrange has a height of exactly 1 row.

Przykład:

W języku Basic

    oDoc.SetValue("A1", 2)
    'Below the Value array is smaller than the TargetRange (remaining cells are emptied)
    oDoc.SetValue("A1:F1", Array(1, 2, 3))
    'Below the Value and TargetRange have the same size
    oDoc.SetValue("A1:D2", SF_Array.AppendRow(Array(1, 2, 3, 4), Array(5, 6, 7, 8)))
  

If you want to fill a single row with values, you can use the Offset function. In the example below, consider that arrData is a one-dimensional array:


    Dim firstCell As String : firstCell = "A1"
    Dim lenArray As Integer : lenArray = UBound(arrData) - LBound(arrData) + 1
    Dim newRange As String : newRange = oDoc.Offset(firstCell, width = lenArray)
    oDoc.SetValue(newRange, arrData)
  
W języku Python

    myDoc.SetValue("A1", 2)
    myDoc.SetValue("A1:F1", (1, 2, 3))
    myDoc.SetValue("A1:D2", ((1, 2, 3, 4), (5, 6, 7, 8)))
  

    firstCell = "A1"
    newRange = doc.Offset(firstCell, width = len(arrData))
    doc.SetValue(newRange, arrData)
  

ShiftDown

Moves a given range of cells downwards by inserting empty rows. The current selection is not affected.

Depending on the value of the wholerow argument the inserted rows can either span the width of the specified range or span all columns in the row.

This method returns a string representing the new location of the initial range.

note

If the shifted range exceeds the sheet edges, then nothing happens.


Składnia:

svc.ShiftDown(range: str, wholerow: bool = False, opt rows: int): str

Parametry:

range: The range above which rows will be inserted, as a string.

wholerow: If set to False (default), then the width of the inserted rows will be the same as the width of the specified range. Otherwise, the inserted row will span all columns in the sheet.

rows: The number of rows to be inserted. The default value is the height of the original range. The number of rows must be a positive number.

Przykład:

W języku Basic

    ' Moves the range "A3:D3" down by one row; affects only columns A to D
    oDoc.ShiftDown("A3:D3")
    ' The inserted row spans all columns in the sheet
    oDoc.ShiftDown("A3:D3", WholeRow := True)
    ' Moves the range "A3:D3" down by five rows
    oDoc.ShiftDown("A3:D3", Rows := 5)
    ' Moves the range "A3:D10" down by two rows and shows the new location of the original range
    Dim sNewRange as String
    sNewRange = oDoc.ShiftDown("A3:D10", Rows := 2)
    MsgBox sNewRange   ' $Sheet1.$A$5:$D$12
  
W języku Python

    myDoc.ShiftDown("A3:D3")
    myDoc.ShiftDown("A3:D3", wholerow = True)
    myDoc.ShiftDown("A3:D3", rows = 5)
    sNewRange = myDoc.ShiftDown("A3:D10", rows = 2)
    bas = CreateScriptService("Basic")
    bas.MsgBox(sNewRange)
  

ShiftLeft

Deletes the leftmost columns of a given range and moves to the left all cells to the right of the affected range. The current selection is not affected.

Depending on the value of the wholecolumn argument the deleted columns can either span the height of the specified range or span all rows in the column.

This method returns a string representing the location of the remaining portion of the initial range. If all cells in the original range have been deleted, then an empty string is returned.

Składnia:

svc.ShiftLeft(range: str, wholecolumn: bool = False, opt columns: int): str

Parametry:

range: The range from which cells will be deleted, as a string.

wholecolumn: If set to False (default), then the height of the deleted columns will be the same as the height of the specified range. Otherwise, the deleted columns will span all rows in the sheet.

columns: The number of columns to be deleted from the specified range. The default value is the width of the original range, which is also the maximum value of this argument.

Przykład:

W języku Basic

    ' Deletes the range "B3:B6"; moves left all cells to the right
    oDoc.ShiftLeft("B3:B6")
    ' Deletes the first column in the range "A3:D6"
    oDoc.ShiftLeft("A3:D6", Columns := 1)
    ' The deleted columns (A to D) spans all rows in the sheet
    oDoc.ShiftLeft("A3:D6", WholeColumn := True)
  
W języku Python

    myDoc.ShiftLeft("B3:B6")
    myDoc.ShiftLeft("A3:D6", Columns = 1)
    myDoc.ShiftLeft("A3:D6", WholeColumn = True)
  

ShiftUp

Deletes the topmost rows of a given range and moves upwards all cells below the affected range. The current selection is not affected.

Depending on the value of the wholerow argument the deleted rows can either span the width of the specified range or span all columns in the row.

This method returns a string representing the location of the remaining portion of the initial range. If all cells in the original range have been deleted, then an empty string is returned.

Składnia:

svc.ShiftUp(range: str, wholerow: bool = False, opt rows: int): str

Parametry:

range: The range from which cells will be deleted, as a string.

wholerow: If set to False (default), then the width of the deleted rows will be the same as the width of the specified range. Otherwise, the deleted row will span all columns in the sheet.

rows: The number of rows to be deleted from the specified range. The default value is the height of the original range, which is also the maximum value of this argument.

Przykład:

W języku Basic

    ' Deletes the range "A3:D3"; moves all cells below it by one row up
    oDoc.ShiftUp("A3:D3")
    ' Deletes the first row in the range "A3:D6"
    oDoc.ShiftUp("A3:D6", Rows := 1)
    ' The deleted rows spans all columns in the sheet
    oDoc.ShiftUp("A3:D6", WholeRow := True)
  
W języku Python

    myDoc.ShiftUp("A3:D3")
    myDoc.ShiftUp("A3:D6", rows = 1)
    myDoc.ShiftUp("A3:D6", wholerow = True)
  

ShiftRight

Moves a given range of cells to the right by inserting empty columns. The current selection is not affected.

Depending on the value of the wholecolumn argument the inserted columns can either span the height of the specified range or span all rows in the column.

This method returns a string representing the new location of the initial range.

note

If the shifted range exceeds the sheet edges, then nothing happens.


Składnia:

svc.ShiftRight(range: str, wholecolumn: bool = False, opt columns: int): str

Parametry:

range: The range which will have empty columns inserted to its left, as a string.

wholecolumn: If set to False (default), then the height of the inserted columns will be the same as the height of the specified range. Otherwise, the inserted columns will span all rows in the sheet.

columns: The number of columns to be inserted. The default value is the width of the original range.

Przykład:

W języku Basic

    ' Moves the range "A3:A6" right by one column; affects only rows 3 to 6
    oDoc.ShiftRight("A3:A6")
    ' Moves the range "A3:A6" right by five columns
    oDoc.ShiftRight("A3:A6", Columns := 5)
    ' The inserted column spans all rows in the sheet
    oDoc.ShiftRight("A3:A6", WholeColumn := True)
  
W języku Python

    myDoc.ShiftRight("A3:A6")
    myDoc.ShiftRight("A3:A6", columns = 5)
    myDoc.ShiftRight("A3:A6", wholecolumn = True)
  

SortRange

Sorts the given range based on a set of columns/rows that are considered as keys. The sorting order may vary by column/row. It returns a string representing the modified range of cells. The size of the modified area is fully determined by the size of the source area.

Składnia:

svc.SortRange(range: str, sortkeys: any, sortorder: any = "ASC", destinationcell: str = "", containsheader: bool = False, casesensitive: bool = False, sortcolumns: bool = False): str

Parametry:

range: The range to be sorted, as a string.

sortkeys: A scalar (if 1 column/row) or an array of column/row numbers starting from 1.

sortorder: A scalar or an array of strings containing the values "ASC" (ascending), "DESC" (descending) or "" (which defaults to ascending). Each item is paired with the corresponding item in sortkeys. If the sortorder array is shorter than sortkeys, the remaining keys are sorted in ascending order.

destinationcell: The destination cell of the sorted range of cells, as a string. If a range is given, only its top-left cell is considered. By default the source Range is overwritten.

containsheader: When True, the first row/column is not sorted.

casesensitive: Only for string comparisons. Default = False

sortcolumns: When True, the columns are sorted from left to right. Default = False : rows are sorted from top to bottom.

Przykład:

W języku Basic

    'Sort range based on columns A (ascending) and C (descending)
    oDoc.SortRange("A2:J200", Array(1, 3), Array("ASC", "DESC"), CaseSensitive := True)
  
W języku Python

    myDoc.SortRange("A2:J200", (1, 3), ("ASC", "DESC"), casesensitive = True)
  
warning

Wszystkie podstawowe procedury lub identyfikatory ScriptForge poprzedzone znakiem podkreślenia „_” są zarezerwowane do użytku wewnętrznego. Nie należy ich używać w makrach Basic ani skryptach Pythona.