著者:荒川 雄介
オープンソースのオフィスソフト「LibreOffice」は、Pythonで記述されたマクロ(簡易スクリプト)を実行できます。しかしデフォルト状態では、Pythonマクロを作成しやすい環境が整備されていません。本特集では、開発環境を整備する手順を中心に、Pythonマクロ作成についての基礎知識を紹介します。使い慣れた言語を使って、LibreOfficeのさまざまな処理を効率化しましょう。
シェルスクリプトマガジン Vol.82は以下のリンク先でご購入できます。![]()
![]()
図3 「Hello!」と書かれたダイアログを表示するPythonマクロのコード
from scriptforge import CreateScriptService
def hello():
bas = CreateScriptService("Basic")
bas.MsgBox("Hello!")
g_exportedScripts = (hello,)
図9 CSVファイルからCalcのシートにデータを読み込むPythonマクロのコード
from scriptforge import CreateScriptService
def load_csv():
cal = CreateScriptService("Calc")
cal.ImportFromCSVFile(r"C:\test.csv", "A1")
g_exportedScripts = (load_csv, )
図11 図9のコードを新規のCalcシートを開くように変更したもの
from scriptforge import CreateScriptService
def load_csv():
ui = CreateScriptService("UI")
cal = ui.CreateDocument("Calc")
cal.ImportFromCSVFile(r"C:\test.csv", "A1")
g_exportedScripts = (load_csv, )
図12 文書ファイルがある場所からCSVファイルを読み込めるように図9のコードを変更したもの
from scriptforge import CreateScriptService
import uno
import os.path
def load_csv():
doc = XSCRIPTCONTEXT.getDocument()
path = uno.fileUrlToSystemPath(doc.URL)
cdir = os.path.dirname(path)
cal = CreateScriptService("Calc")
cal.ImportFromCSVFile(cdir + r"\test.csv", "A1")
g_exportedScripts = (load_csv, )
図13 データベースからデータを読み込んで集計/グラフ表示をするPythonマクロのコード
from scriptforge import CreateScriptService
def importdata():
# データベースからデータを取得
db=CreateScriptService('database',registrationname='Bibliography')
sql='SELECT [Custom1] AS [Language],[Identifier] FROM [biblio] ORDER BY [Language] ASC'
data=db.GetRows(sql,header=True)
db.CloseDatabase()
# 取得したデータをシートにコピー
calc=CreateScriptService("Calc")
datarange=calc.setArray('Sheet1.A1',data)
# ピボットテーブルを作成して集計
pivot=calc.CreatePivotTable('Pivot1',datarange,targetcell='D1',
datafields='Identifier;Count',rowfields='Language',
rowtotals=False,columntotals=False,filterbutton=False)
# グラフを作成
chart=calc.CreateChart('NumberByLanguage','Sheet1',pivot,rowheader=True,
columnheader=True)
chart.ChartType, chart.Dim3D,chart.Legend='Pie',True,True
chart.Resize(4000, 3000, 7000, 2500)
g_exportedScripts = (importdata, )
図18 図9のコードをイベント駆動できるように修正
from scriptforge import CreateScriptService
def load_csv(args=None):
cal = CreateScriptService("Calc")
cal.ImportFromCSVFile(r"C:\test.csv", "A1")
g_exportedScripts = (load_csv, )
図19 Calcのシート(Sheet1)の内容をすべて消去するPythonマクロのコード
from scriptforge import CreateScriptService
def clear(args=None):
calc=CreateScriptService("Calc")
calc.ClearAll('Sheet1.*')
g_exportedScripts = (clear, )
図20 外部ライブラリ(NumPy)を利用するythonマクロのサンプルコード
from scriptforge import CreateScriptService
import numpy as np
def test_numpy():
A = np.array([1, 2, 3, 4, 5, 6]).reshape(2,3)
B = A + 10
cal = CreateScriptService("Calc")
cal.setArray("A1", B.tolist())
g_exportedScripts = (test_numpy, )