How to Run Python Scripts in LibreOffice Calc Macros

Yes. LibreOffice Calc can run Python code as a macro inside the LibreOffice process, and a LibreOffice Basic macro can also call a Python function through LibreOffice's scripting framework. If your goal is to read or change cells in the open spreadsheet, an in-process Python macro is usually the simplest starting point. Use a Basic-to-Python call when an existing Basic macro should hand one task to a reusable Python function.

These approaches are different from launching an ordinary system Python script with a shell command. A normal external Python process does not automatically receive Calc's document object. For workbook access, run a Python macro through LibreOffice or deliberately connect an external process to a LibreOffice instance through UNO.

What does “run Python inside a Calc macro” mean?

LibreOffice supports multiple scripting languages through its scripting framework. In a Python macro, LibreOffice supplies a UNO context object that lets the script reach the current document and its sheets. A Python macro is a function in a .py module; the module's g_exportedScripts tuple identifies functions that LibreOffice should show as runnable macros.

A Python macro can run on its own from Calc's macro menu. It does not have to be called by Basic. If you already have a Basic macro and want it to call Python, LibreOffice's script provider or the newer ScriptForge Session.ExecutePythonScript service can bridge the two languages.

Which approach should you choose?

  • Use a Python macro directly when the task is mostly Python and needs the current Calc document. It avoids a language handoff and is easiest to debug as one script.
  • Call Python from Basic when you already have Basic code, buttons, or document events that should remain in place, and you want a Python helper to perform a focused calculation or data operation.
  • Use an external Python process when you need a separate development environment or Python packages not included with LibreOffice. Set up an explicit UNO connection; do not assume a script started from a terminal can see the open spreadsheet.

For example, a small spreadsheet cleanup tool can be written entirely as a Python macro. If an existing Basic button already runs a report, keep the button's macro and let it call a Python function that computes the report total.

How do you create a Python macro that edits Calc cells?

LibreOffice 將個人 Python 腳本儲存在使用者設定檔中,將應用程式範圍的腳本儲存在安裝目錄中,並將文件腳本儲存在文件中。對於首次測試,使用個人腳本很方便,因為同一用戶在任何開啟的 LibreOffice 文件中都可以存取它。但是,個人腳本不會隨 ODS 檔案一起傳輸,因此其他人不會自動收到它。

在 LibreOffice 說明的「Python 腳本組織和位置」部分,找到您系統對應的個人 Python 腳本資料夾。常見位置包括%APPDATA%\LibreOffice\4\user\Scripts\pythonWindows 和~/.config/libreoffice/4/user/Scripts/pythonLinux 系統。實際的設定檔位置可能有所不同;請使用您系統安裝文件中記錄的位置,而不是憑猜測建立第二個設定檔目錄。

calc_tools.py在個人 Python 腳本資料夾中建立一個名為 `.python` 的文件,然後新增以下簡單範例:

def double_a1(args=None):
    doc = XSCRIPTCONTEXT.getDocument()
    sheet = doc.getCurrentController().getActiveSheet()

    source = sheet.getCellRangeByName("A1")
    target = sheet.getCellRangeByName("B1")
    target.setValue(source.getValue() * 2)

g_exportedScripts = (double_a1,)

此函數讀取活動工作表儲存格 A1 中的數值,並將其兩倍的值寫入儲存格 B1。XSCRIPTCONTEXT函數在運行時傳遞給 LibreOffice Python 巨集;當在 LibreOffice 外部開啟相同檔案時,它不是常規的 Python 全域變數。此公用函數已列入g_exportedScripts巨集選擇器,因此會出現在巨集選擇器中。

儲存文件,然後開啟或返回 Calc,選擇「工具」>「巨集」>「執行巨集」。根據 LibreOffice 版本或平台翻譯的不同,選單標籤可能只有一個。選擇“我的巨集”>“calc_tools”>“double_a1”並執行它。首先在 A1 中輸入一個數字,然後檢查 B1 中是否包含該數字的兩倍值。如果模組未顯示,請確認檔案副檔名是否正確.py,檔案是否位於正確的設定檔 Python 資料夾中,以及是否已安裝 Python 腳本支援。新增模組後重新啟動 LibreOffice 有助於刷新腳本清單。

Basic 巨集如何呼叫 Python 函數?

要進行 Basic 到 Python 的調用,請將 Python 模組放在個人腳本資料夾中,然後透過 ScriptForgeSession服務調用其函數。此範例使用 Python 將兩個值相加,並將結果寫入目前 Calc 工作表的 B1 儲存格。

在 中calc_tools.py,定義函數:

def add_values(first, second):
    return float(first) + float(second)

g_exportedScripts = (add_values,)

然後,在 Calc 中建立一個基本巨集並使用它:

Sub RunPythonHelper()
    Dim session As Object
    Dim result As Variant
    Dim sheet As Object

    session = CreateScriptService("Session")
    result = session.ExecutePythonScript( _
        session.SCRIPTISPERSONAL, _
        "calc_tools.py$add_values", _
        12, 30)

    sheet = ThisComponent.CurrentController.getActiveSheet()
    sheet.getCellRangeByName("B1").setValue(result)
End Sub

從基本巨集選擇器運行RunPythonHelper。如果呼叫成功,B1 應顯示 42。腳本引用遵循以下格式module.py$function_name;對於子資料夾或其他儲存位置中的模組,請使用該 ScriptForge 版本文件中記錄的語法和位置常數。參數和傳回值應使用兩種語言都能清晰表示的資料類型,例如數字、字串和簡單序列。

CreateScriptServiceScriptForge 提供的會話助理在現代 LibreOffice 版本中可用,但選單名稱和捆綁元件在舊版本或發行版中可能有所不同。如果此服務不可用,請使用 LibreOffice 文件中提供的 UNO 腳本提供者方法,該方法XScript從腳本 URI 取得並呼叫它。避免在未更改巨集位置設定的情況下,將程式碼片段複製到其他巨集位置。

Python 程式碼應該是個人使用的、共享的還是嵌入式的?

貯存最佳匹配權衡
我的巨集/用戶個人資料您在文件中可重複使用的自訂工具發送電子表格時不會自動包含在內
應用程式巨集在一個安裝環境中為多個使用者管理腳本通常需要管理員權限才能安裝或維護
文件巨集旨在與單一文檔關聯的程式碼收件者可能需要允許巨集;請在目標 LibreOffice 版本上測試可移植性和安全性

對於團隊工作流程,在圍繞個人巨集建立工作簿之前,請先確定接收者如何取得並信任程式碼。如果 Python 邏輯必須與電子表格一起提供,請在接收者使用的相同 LibreOffice 版本上測試文件的巨集儲存和安全性提示。對於託管部署,管理員可以為使用者打包腳本,或在組織正常的軟體控制下分發擴充功能。

為什麼巨集會缺失或運行失敗?

  • Python 選項或模組缺失。在某些 GNU/Linux 發行版中,LibreOffice 的 Python 腳本框架是一個可選軟體包。如果 Python 巨集未出現在巨集對話方塊中,請檢查發行版的 LibreOffice 軟體套件說明。
  • 腳本保存在錯誤的設定檔中。 LibreOffice可以使用多個使用者設定檔。請確認目前執行的 LibreOffice 安裝的設定檔路徑,並將模組儲存到該Scripts/python設定檔目錄下。
  • 該函數尚未導出。如果您打算透過巨集選擇器執行函數,請將其新增至匯出清單g_exportedScripts。請確保元組語法中包含尾隨逗號(適用於單元素元組)。
  • 該腳本在 LibreOffice 之外運行。 XSCRIPTCONTEXT它只存在於 LibreOffice 啟動的巨集中,而非使用系統python指令啟動相同檔案時。請使用巨集運行器或設定已記錄的 UNO 連線。
  • 巨集安全設定會阻止嵌入程式碼。請檢查 LibreOffice 的巨集安全設置,並僅啟用來自可信任來源的程式碼。降低全域安全等級並非有效的故障排除捷徑。
  • 導入的模組無法存取文件上下文。 LibreOffice文件XSCRIPTCONTEXT不會將全域上下文傳遞給導入的模組。請將所需的文件或工作表物件傳遞給輔助函數,而不是期望匯入的模組讀取該全域上下文。
  • 沒有可見的控制台輸出。從「工具」>「巨集」選單執行巨集時,Python 的標準輸出不可用。如需回饋,請將結果寫入儲存格、使用 LibreOffice 對話方塊服務或將日誌記錄到指定的檔案路徑。

如何安全地驗證結果?

使用電子表格副本和已知輸入進行測試。確認 Python 巨集出現在運行器中,運行一次,並將輸出單元格與手動計算的結果進行比較。對於 Basic 到 Python 的調用,測試一個簡單的輸入,並確認返回值已寫入目標工作表。避免使用會刪除工作表、覆蓋大範圍資料或執行作業系統指令的腳本。

測試成功後,確定腳本在其他電腦上的安裝方式,並記錄所需的 Python 庫或 LibreOffice 版本要求。 LibreOffice 自帶的 Python 環境用於進程內宏;為其他系統 Python 解釋器安裝的軟體包可能無法使用。如果需要其他解釋器的軟體包,請使用外部進程/UNO 方法,並進行相應的連接配置。

官方參考資料

留下評論

如何在 Microsoft Word 中移動圖片

如何在 Microsoft Word 中移動圖片

學習如何在 Word 中拖曳圖片、選擇文字環繞方式、將圖片與段落保持在一起或將其固定在頁面上,以及如何解決圖片無法移動的問題。

如何在 Excel 中插入複選框:兩種簡易方法

如何在 Excel 中插入複選框:兩種簡易方法

學習如何使用儲存格內工具在 Excel 中插入複選框,使用公式計算選取項目的數量,或在舊版桌面 Excel 中新增連結的表單控制項。

如何在 Excel 中自動填充字母:從 A 到 Z 及其他

如何在 Excel 中自動填充字母:從 A 到 Z 及其他

使用填充柄公式、SEQUENCE 或可重複使用的自訂清單在 Excel 中產生 A 到 Z、小寫字母或 Z 以上的標籤。

如何在 Excel 中新增刪除線:快捷鍵和逐步指南

如何在 Excel 中新增刪除線:快捷鍵和逐步指南

學習如何在 Windows、Mac 和網頁版 Excel 中新增刪除線、設定儲存格部分格式以及刪除線條而不刪除其值。

什麼是 Microsoft Access?它的資料庫工具是如何運作的?

什麼是 Microsoft Access?它的資料庫工具是如何運作的?

Microsoft Access 是一款 Windows 資料庫應用程序,用於儲存相關記錄、建立查詢、建立資料輸入表單和產生報表。了解它的工作原理以及適用場景。

如何在 Word 2010 中變更網格線高度和寬度

如何在 Word 2010 中變更網格線高度和寬度

了解如何在 Word 2010 中調整網格線高度和寬度、變更可見線頻率以及設定底層水平和垂直繪圖網格間距。

Office Outlook 2010 匯入和匯出:使用 PST 檔案移動數據

Office Outlook 2010 匯入和匯出:使用 PST 檔案移動數據

了解如何將 PST 檔案匯入 Outlook 2010 或匯出郵件、聯絡人、行事曆和任務。按照正確的選單操作,避免遺漏資料夾或重複文件。

使用 Nucleus Kernel 還原 Outlook PST 密碼

使用 Nucleus Kernel 還原 Outlook PST 密碼

使用 Kernel 的目前步驟還原忘記的 Outlook PST 密碼,包括如何識別正確的檔案、進行備份以及檢查工具的限制。

如何在 PowerPoint 幻燈片中插入網頁鏈接

如何在 PowerPoint 幻燈片中插入網頁鏈接

使用 LiveWeb 外掛程式將網站放置在 PowerPoint 投影片上,設定其大小和刷新行為,並在簡報前檢查相容性。

如何在 Word 2010 中變更預設字體和正文樣式

如何在 Word 2010 中變更預設字體和正文樣式

在 Word 2010 中設定預設字體、字號和文字效果,將選擇儲存到 Normal.dotm,然後修改 Normal 樣式以用於以後的文件。