Developer's GuideのJavaの例を動かそうと思ったのですが動かせなかったので、体系的に習得するのは断念します。LibreOffice Calcの課題を決めてネットで検索しながらPythonマクロを習得していきます。
課題1:LibreOffice CalcのPythonマクロを動かす
LibreOffice(2)Pythonの統合開発環境PyCharmのインストールからLibreOffice(4)PyCharmからLibreOfficeを動かす(オートメーション)までの設定をした状態で行います。
まずはLibreOffice Calcのシートに働きかけるPythonマクロが動くのかを確認します。
OOoPython/CalcOverView - ...?の例を利用させていただきます。
LibreOffice(3)PyCharmで作ったマクロをLibreOfficeから実行するでやったようにPyCharmでkadai1.pyファイルを作成します。
LibreOffice(4)PyCharmからLibreOfficeを動かすの以下の例をそのファイルに入力します。
行頭の空白はスペースではなくタブであることに注意してください。
def HelloWorld_Writer():
doc = XSCRIPTCONTEXT.getDocument()
doc.getText().setString("Hello World!")
if __name__ == "__main__":
import unopy
XSCRIPTCONTEXT = unopy.connect()
if not XSCRIPTCONTEXT:
print("Failed to connect.")
import sys
sys.exit(0)
HelloWorld_Writer()
これの1行目から3行目をOOoPython/CalcOverView - ...?の例の2行目から18行目に置き換えます。最後の行のHelloWorld_Writer()をcalc_overview()に置き換えて以下のようになります。
def calc_overview():
doc = XSCRIPTCONTEXT.getDocument()
if doc.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
sheets = doc.getSheets()
sheet = sheets.getByIndex(0)
cellrange = sheet.getCellRangeByPosition(0,0,2,5)
cellrange.getCellByPosition(0,0).setString(u'みかん')
cellrange.getCellByPosition(1,0).setString(u'りんご')
subrange = cellrange.getCellRangeByPosition(0,1,2,5)
rangeAddress = subrange.RangeAddress
for i in range(rangeAddress.EndRow - rangeAddress.StartRow):
for j in range(rangeAddress.EndColumn - rangeAddress.StartColumn):
subrange.getCellByPosition(j,i).setValue((i+1)*(j+2))
if __name__ == "__main__":
import unopy
XSCRIPTCONTEXT = unopy.connect()
if not XSCRIPTCONTEXT:
print("Failed to connect.")
import sys
sys.exit(0)
calc_overview()
(2017.8.25追記。6行目のcellrangeは行1から行6、列Aから列Cまで取得しています。getCellRangeByPosition()の4つの引数のLeft、Top、Right、Bottomは4隅のセルのインデックスを表します。インデックスというのは0から始まるので、getCellRangeByPosition(0,0,2,5)は列A、行1、列C、行6を表すことになります。)LibreOffice(4)PyCharmからLibreOfficeを動かす(オートメーション)で作ったLibreOffice_socket.batでLibreOfficeを起動後「表計算ドキュメント」を開きます。
PyCharmで開いているkadai1.pyのなかで右クリックして「Run 'kadai1'」を選択。
うまくいけばLibreOffice Calcのシートにこのように入力されたはずです。
Pythonでは行頭のタブがすごく重要な意味を持つのでうまくいかないときはPtyCharmで実行後に下の出力ログにでてくるエラーメッセージに指摘された行を再点検します。
PyCharmからマクロを起動する必要がなければ14行目のif __name__ == "__main__":以降の行は不要になります。
参考にしたサイト
OOoPython/CalcOverView - ...?
LibreOffice Calcのシートに働きかけるPythonの例。課題1に使わせて頂きました。



0 件のコメント:
コメントを投稿