1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LibreOffice PythonマクロでWriterにスプレッドシート風の表を作成する

Last updated at Posted at 2018-03-12
実行した環境

Ubuntu Stdio 17.10
LibreOffice 6.0

Apache OpenOfficeのHPには有用な情報・サンプルがたくさんあります。

今回も探している情報ではありませんが、知らない情報がわんさかあります。
HPのトップから探してもたどり着かないので「Apache OpenOffice python」等で検索すると沢山ヒットします。

Writerにスプレッドシート風の表を作成する

今迄、Writerの表に数式が使用できるなど知りませんでしたが、手作業で表コマンドに数式を入れてもちゃんと計算してくれます。
しかし、Calcほど使い勝手はよくありません。
また、全ての関数が使えるわけではないようです。
=<A1> + <B1>  (< >は半角文字です。)
=A1 + B1  (Calcの場合)

Writer_Cell.py
# import uno  #不要
# import unohelper  #不要

def InsertCell():
  doc = XSCRIPTCONTEXT.getDocument()
  text = doc.Text
  cursor = text.createTextCursor()

  table = doc.createInstance( "com.sun.star.text.TextTable" )
  table.initialize( 5,4)  #(行数,列数) 

  text.insertTextContent( cursor, table, 0 )  #表を作成

  table.getCellByName("A1").createTextCursor().setPropertyValue( "CharColor", 3710932 )  #textColor
  table.getCellByName("A1").setPropertyValue( "BackColor", 13421823 )  #BackColor
  table.getCellByName("A1").setString("都道府県")
  table.getCellByName("B1").setString("男人口")
  table.getCellByName("C1").setString("女人口")
  table.getCellByName("D1").setString("小計")

  table.getCellByName("A2").setString("大阪府")
  table.getCellByName("B2").setValue(10000)
  table.getCellByName("C2").setValue(10000)
  table.getCellByName("D2").setFormula("sum <B2:C2>")

  table.getCellByName("A3").setString("京都府")
  table.getCellByName("B3").setValue(9000)
  table.getCellByName("C3").setValue(9000)
  table.getCellByName("D3").setFormula("sum <B3:C3>")

  table.getCellByName("A4").setString("奈良県")
  table.getCellByName("B4").setValue(8000)
  table.getCellByName("C4").setValue(8000)
  table.getCellByName("D4").setFormula("sum <B4:C4>")

  table.getCellByName("C5").setString("合計")
  table.getCellByName("D5").setFormula("sum <D2:D4>")

"A1"セルの( "BackColor", 13421823 )color codeは「13421823」と10進数になっていますが、わかりにくいので「0xCCCCFF」のように16進数表記にしたほうがわかりやすいです。
(下の表は色の指定をしていません。)

fuyou.png

PyUNO samples
https://wiki.openoffice.org/wiki/PyUNO_samples

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?