C# による OpenOffice (LibreOffice) Calc の操作(1) で作成したプログラムの改良を行う。
セットアップ
LibreOffice を C# で操作するためのセットアップ(インストール)はこちらを参照。
実装
非表示モードで操作する
変更点
+using unoidl.com.sun.star.beans; // Property + // 非表示(invisible)で操作するための属性を作成し付与する + PropertyValue[] args1 = new PropertyValue[1]; + args1[0] = new PropertyValue() + { + Name = "Hidden", + Value = new uno.Any((Boolean)true), + }; + // 既存の Excel ファイルを開く - XSpreadsheetDocument doc = (XSpreadsheetDocument)loader.loadComponentFromURL(path, "_blank", 0, null); + XSpreadsheetDocument doc = (XSpreadsheetDocument)loader.loadComponentFromURL(path, "_blank", 0, args1);
コード全文
using System; using uno.util; // Bootstrap using unoidl.com.sun.star.frame; // XComponentsLoader using unoidl.com.sun.star.lang; // XMultiServiceFactory using unoidl.com.sun.star.sheet; // XSpreadsheetDocument, XSpreadsheet using unoidl.com.sun.star.table; // XCell using unoidl.com.sun.star.uno; // XComponentContext using unoidl.com.sun.star.beans; // Property using System.Drawing; class Savings { static void Main(string[] args) { var path = @"file:///c:/Users/neko/cs/LibreOfficeSample/Input.xlsx"; // コンポーネントコンテキストオブジェクトを取得する XComponentContext context = Bootstrap.bootstrap(); // サービスマネージャの取得 XMultiServiceFactory factory = (XMultiServiceFactory)context.getServiceManager(); // コンポーネントローダオブジェクトを生成する XComponentLoader loader = (XComponentLoader)factory.createInstance("com.sun.star.frame.Desktop"); // 非表示(invisible)で操作するための属性を作成し付与する PropertyValue[] args1 = new PropertyValue[1]; args1[0] = new PropertyValue() { Name = "Hidden", Value = new uno.Any((Boolean)true), }; // 以上で準備が完了したので, LibreOffice のアプリ(Calc, Base, Draw など) の起動が可能になった // 既存の Excel ファイルを開く XSpreadsheetDocument doc = (XSpreadsheetDocument)loader.loadComponentFromURL(path, "_blank", 0, args1); // シートオブジェクトを取得する XSpreadsheets sheets = doc.getSheets(); //「Sheet1」シートにアクセスする XSpreadsheet sheet = (XSpreadsheet)sheets.getByName("Sheet1").Value; // B2 セルにアクセスする XCell cell = sheet.getCellByPosition(1, 0); // B列、1行目 Console.WriteLine("{0}", cell.getFormula()); cell.setFormula("レート"); // セルに文字列代入 Console.WriteLine("{0}", cell.getFormula()); cell = sheet.getCellByPosition(1, 0); // セルを選択(B列、1行目) cell.setValue(110.23); // セルに数値代入 Console.WriteLine("{0}", cell.getValue()); } }
ビルド
ソースファイル LibreOfficeSample.cs と同じ階層に *.dll を配置した場合、次のようになる。
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /nologo /r:.\cli_basetypes.dll /r:.\cli_cppuhelper.dll /r:.\cli_oootypes.dll /r:.\cli_uno.dll /r:.\cli_ure.dll /r:.\cli_uretypes.dll /out:a.exe .\LibreOfficeSample.cs