#はじめに
- [C# で LibreOffice を操作する]
(http://home.a00.itscom.net/hatada/libreoffice/calc/libreoffice_calc01.html) - [Excelの参照を追加せずにExcelを使う[C#] | zenmai software]
(https://zenmai.wordpress.com/2011/06/24/excel%e3%81%ae%e5%8f%82%e7%85%a7%e3%82%92%e8%bf%bd%e5%8a%a0%e3%81%9b%e3%81%9a%e3%81%abexcel%e3%82%92%e4%bd%bf%e3%81%86c/)
を参考にさせて頂きました。圧倒的感謝……!
#環境
- Windows 10 Home (64bit)
- Visual Studio Community 2019
#サンプルソース
##JScript
libreoffice.js
{
var factory = WScript.CreateObject("com.sun.star.ServiceManager");
var loader = factory.createInstance("com.sun.star.frame.Desktop");
var doc = loader.loadComponentFromURL("file:///C:/data/test.ods", "_blank", 0, []);
var sheets = doc.getSheets();
var sheet = sheets.getByName("Sheet1");
var cell = sheet.getCellByPosition(0, 0);
cell.setFormula("hello, world");
}
##VB.NET
Module1.vb
Module Module1
Sub Main()
Dim factory, loader, doc As Object
Dim d(0) As Object
factory = CreateObject("com.sun.star.ServiceManager")
loader = factory.createInstance("com.sun.star.frame.Desktop")
doc = loader.loadComponentFromURL("private:factory/scalc", "_blank", 0, d)
Dim sheets, sheet, cell As Object
sheets = doc.getSheets()
sheet = sheets.getByName("Sheet1")
cell = sheet.getCellByPosition(1, 1)
cell.setFormula("hello, world")
End Sub
End Module
##C#
LibreOffice SDKを使う方法もあるが、使わない方法もある。
Program.cs
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var t = Type.GetTypeFromProgID("com.sun.star.ServiceManager");
var factory = Activator.CreateInstance(t);
object[] a = { "com.sun.star.frame.Desktop" };
var loader = factory.GetType().InvokeMember("createInstance",
BindingFlags.InvokeMethod, null, factory, a);
object[] b = { };
object[] c = { "private:factory/scalc", "_blank", 0, b };
var doc = loader.GetType().InvokeMember("loadComponentFromURL",
BindingFlags.InvokeMethod, null, loader, c);
Marshal.ReleaseComObject(factory);
}
}
}