使用OpenOffice Uno CLI和C#创建电子表格

lan*_*oxx 4 c# openoffice.org uno

到目前为止,我已经找到了几个讨论ODS文件创建的来源:如何在.Net中创建ODS文档以及 如何使用C#.NET创建.odt文件?

最有趣的是打开calc文件的解释.然而,这会在全屏幕中打开OpenOffice,我正在寻找的是一种写入Calc文件(.ods)而不实际打开Openoffice的方法.这样我就可以编写一个只打开savefiledialog的函数,获取文件名,然后创建并保存.ods文件.

是否有任何C#代码示例可用于执行此类操作?

lan*_*oxx 6

所以我终于解决了这个问题,并希望能够拯救其他人再次经历这个问题的榛子.HEADACE的基本要点是:

  1. 使用正斜杠而不是反斜杠(例如,C:/不是C:\)
  2. Filtername使用应设置为用来保存文档的引擎.可能的值包括writer8,calc8,MS Excel 97,所以对于电子表格你显然需要使用calc8
  3. 如果您不希望OpenOffice在forground中弹出并等待它填满您的数据,那么使用PropertyValue和设置Hiddentrue.

快乐编码,不要忘记安装OpenOffice SDK,以便能够添加unoidl引用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.table;
using unoidl.com.sun.star.text;

namespace TimeScanner {
    class ReportGenerator {
        private const string fileName = 
            @"file:///C:/Documents and Settings/My Documents/Hours Report.ods";

        //Concrete Methods
        internal XComponent openCalcSheet() {
            XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
            XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
            XComponentLoader desktop = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");
            string url = @"private:factory/scalc";
            PropertyValue[] loadProps = new PropertyValue[1];
            loadProps[0] = new PropertyValue();
            loadProps[0].Name = "Hidden";
            loadProps[0].Value = new uno.Any(true);
            //PropertyValue[] loadProps = new PropertyValue[0];
            XComponent document = desktop.loadComponentFromURL(url, "_blank", 0, loadProps);
            return document;
        }

        public void writeToSheet(XComponent document) {
            XSpreadsheets oSheets = ((XSpreadsheetDocument)document).getSheets();
            XIndexAccess oSheetsIA = (XIndexAccess) oSheets;
            XSpreadsheet sheet = (XSpreadsheet) oSheetsIA.getByIndex(0).Value;
            XCell cell = sheet.getCellByPosition( 0, 0 ); //A1
            ((XText)cell).setString("Cost");
            cell = sheet.getCellByPosition( 1, 0 ); //B1
            cell.setValue(200);
            cell = sheet.getCellByPosition( 1, 2 ); //B3
           cell.setFormula("=B1 * 1.175");
        }

        public void saveCalcSheet(XComponent oDoc) {        
            PropertyValue[] propVals = new PropertyValue[1];
            propVals[0] = new PropertyValue();
            propVals[0].Name = "FilterName";
            propVals[0].Value = new uno.Any("calc8");
            ((XStorable)oDoc).storeToURL(fileName, propVals);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)