C#操作openoffice writer文档

</pre>主要的功能是实现对openoffice writer文档的新建、保存、插入表格、图片等<pre name="code" class="csharp">//References are: you can find them in the GAC or in the 3.x sdk 
//cli_basetypes.dll 
//cli_cppuhelper.dll 
//cli_oootypes.dll 
//cli_uno.dll 
//cli_ure.dll 
//cli_uretypes.dll 

using System; 
using System.Collections; 
using System.Runtime.InteropServices; 
using System.Text; 
//For Marshal and Registry 
using Microsoft.Win32; 
/* 
* Add all needed CLI namespaces to the current class. 
*/ 
using unoidl.com.sun.star.lang; 
using unoidl.com.sun.star.uno; 
using unoidl.com.sun.star.bridge; 
using unoidl.com.sun.star.frame; 
using unoidl.com.sun.star.text; 
using uno.util; 

namespace OOOCLI 
{ 
    class OpenOfficeApp 
    { 
        //Define a file name. Change this to an existing path! 
        private static string FileName = @"F:\odtfiles\test.odt"; 
        
            public static void OOOStart() 
        { 
            // ***********************    Connection 
            //Necessary with OOO3 and NetFramework less than 3.5 (see: 
            //   http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/ProUNO/CLI/CLI_Language_Binding 
            // & http://blog.nkadesign.com/2008/net-working-with-openoffice-3/ . 
            InitOpenOfficeEnvironment(); 

            //From Lars Behrmann: OpenOffice programming with C# / .net http://www.opendocument4all.com/ 
            
            // ***********************    First Steps to Load a document 
            //Call the bootstrap method to get a new ComponentContext object. 
            //If OpenOffice isn't already started this will start it and then return the ComponentContext. 
            unoidl.com.sun.star.uno.XComponentContext localContext = uno.util.Bootstrap.bootstrap(); 

            //Get a new service manager of the MultiServiceFactory type 
            //we need this to get a desktop object and create new CLI objects. 
            unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager(); 
            
            //Create a new Desktop instance using our service manager 
            //Notice: We cast our desktop object to XComponent loader 
            //so that we could load or create new documents. 
            XComponentLoader componentLoader =(XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop"); 
            
            //Create a new blank writer document using our component loader object. 
            XComponent xComponent = componentLoader.loadComponentFromURL( 
            "private:factory/swriter", //a blank writer document 
            "_blank", 0, //into a blank frame use no searchflag 
            new unoidl.com.sun.star.beans.PropertyValue[0]);//use no additional arguments. 

            // ***********************    Working with text 
            // -------------------      First and simple Method 
            //Cast our component to a the XText interface 
            
            //and write some simple text into document. 
           // ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().setString("Hello I'm the first text!"); 

            // From sdk WriterDemo.vb translate and enhanced to C# by Marc FEGLI http://pagesperso-orange.fr/hffm/index.html 
            // -------------------      Second and complete Method 
            Cast our component to a the XText interface: Create a text object 
            XText xText = ((XTextDocument)xComponent).getText(); 
            XSimpleText xSimpleText = (XSimpleText)xText; 

            //Create a cursor object 
            XTextCursor xCursor = xSimpleText.createTextCursor(); 
            // C# characters for Backspace ... "\r" and "\n" 
            //Inserting some Text 
            xText.insertString(xCursor, "The first line in the newly created text document." + "\r", false); 

            //Create instance of a text table with 4 columns and 4 rows 
            object objTextTable = null; 
            objTextTable = ((XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.TextTable"); 
            XTextTable xTextTable = (XTextTable)objTextTable; 
            xTextTable.initialize(4, 4); 
            xText.insertTextContent(xCursor, xTextTable, false); 


            //Set the table background color 
            // Get XPropertySet interfaces from Table object 
            unoidl.com.sun.star.beans.XPropertySet xPropertySetTable = (unoidl.com.sun.star.beans.XPropertySet)objTextTable; 
            xPropertySetTable.setPropertyValue("BackTransparent", new uno.Any(false)); 
            xPropertySetTable.setPropertyValue("BackColor", new uno.Any(0xccccff)); 

            //Get first row 
            unoidl.com.sun.star.table.XTableRows xTableRows = xTextTable.getRows(); 
            uno.Any anyRow = default(uno.Any); 
            anyRow = ((unoidl.com.sun.star.container.XIndexAccess)xTableRows).getByIndex(0); 

            //Set a different background color for the first row 
            // Get XPropertySet interface from Row object 
            unoidl.com.sun.star.beans.XPropertySet xPropertySetFirstRow = (unoidl.com.sun.star.beans.XPropertySet)anyRow.Value; 
            xPropertySetFirstRow.setPropertyValue("BackTransparent", new uno.Any(false)); 
            xPropertySetFirstRow.setPropertyValue("BackColor", new uno.Any(0x6666aa)); 
            
            //Fill the first table row 
            //Delegate Methods: see insertIntoCell 
            insertIntoCell("A1", "FirstColumn", xTextTable); 
            insertIntoCell("B1", "SecondColumn", xTextTable); 
            insertIntoCell("C1", "ThirdColumn", xTextTable); 
            insertIntoCell("D1", "SUM", xTextTable); 

            //Fill the remaining rows 
            xTextTable.getCellByName("A2").setValue(22.5); 
            xTextTable.getCellByName("B2").setValue(5615.3); 
            xTextTable.getCellByName("C2").setValue(-2315.7); 
            xTextTable.getCellByName("D2").setFormula("sum <A2:C2>"); 

            xTextTable.getCellByName("A3").setValue(21.5); 
            xTextTable.getCellByName("B3").setValue(615.3); 
            xTextTable.getCellByName("C3").setValue(-315.7); 
            xTextTable.getCellByName("D3").setFormula("sum <A3:C3>"); 

            xTextTable.getCellByName("A4").setValue(121.5); 
            xTextTable.getCellByName("B4").setValue(-615.3); 
            xTextTable.getCellByName("C4").setValue(415.7); 
            xTextTable.getCellByName("D4").setFormula("sum <A4:C4>"); 

            //Change the CharColor and add a Shadow 
            // Get XPropertySet interface from Cursor object 
            unoidl.com.sun.star.beans.XPropertySet xPropertySetCursor = (unoidl.com.sun.star.beans.XPropertySet)xCursor; 
            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(255)); 
            xPropertySetCursor.setPropertyValue("CharShadowed", new uno.Any(true)); 

            //Create a paragraph break 
            xSimpleText.insertControlCharacter(xCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); 

            //Inserting colored Text. 
            xSimpleText.insertString(xCursor, " This is a colored Text - blue with shadow" + "\r", false); 

            //Create a paragraph break 
            xSimpleText.insertControlCharacter(xCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); 

            //Create a GraphicObject. 
            object objGraphicObject = null; 
            objGraphicObject = ((unoidl.com.sun.star.lang.XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.GraphicObject"); 

            unoidl.com.sun.star.text.XTextContent xGraphicObject = (unoidl.com.sun.star.text.XTextContent)objGraphicObject; 

            //Set the size of the GraphicObject 
            unoidl.com.sun.star.awt.Size GraphicObjectSize = new unoidl.com.sun.star.awt.Size(5000, 5000); 
            ((unoidl.com.sun.star.drawing.XShape)xGraphicObject).setSize(GraphicObjectSize); 

            //Set anchortype 
            unoidl.com.sun.star.beans.XPropertySet xPropertySetGraphicObject = (unoidl.com.sun.star.beans.XPropertySet)xGraphicObject; 
            xPropertySetGraphicObject.setPropertyValue("AnchorType", new uno.Any(typeof(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER)); 

            //Set Picture path: 
            // First Method with OOO notation for Windows Notation see PathConverter method 
            xPropertySetGraphicObject.setPropertyValue("GraphicURL", new uno.Any("file:///C:/test.jpg")); 
            
            //insert the GraphicObject 
            xText.insertTextContent(xCursor, xGraphicObject, false); 

            //Create a TextFrame. 
            object objTextFrame = null; 
            objTextFrame = ((unoidl.com.sun.star.lang.XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.TextFrame"); 

            unoidl.com.sun.star.text.XTextFrame xTextFrame = (unoidl.com.sun.star.text.XTextFrame)objTextFrame; 

            //Set the size of the frame 
            unoidl.com.sun.star.awt.Size FrameSize = new unoidl.com.sun.star.awt.Size(15000, 400); 
            ((unoidl.com.sun.star.drawing.XShape)xTextFrame).setSize(FrameSize); 

            //Set anchortype 
            unoidl.com.sun.star.beans.XPropertySet xPropertySetFrame = (unoidl.com.sun.star.beans.XPropertySet)xTextFrame; 
            xPropertySetFrame.setPropertyValue("AnchorType", new uno.Any(typeof(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER)); 

            //insert the frame 
            xText.insertTextContent(xCursor, xTextFrame, false); 

            //Get the text object of the frame 

            unoidl.com.sun.star.text.XText xFrameText = xTextFrame.getText(); 

            unoidl.com.sun.star.text.XSimpleText xFrameSimpleText = (unoidl.com.sun.star.text.XSimpleText)xFrameText; 

            //Create a cursor object 
            unoidl.com.sun.star.text.XTextCursor xFrameCursor = xFrameSimpleText.createTextCursor(); 

            //Inserting some Text 
            xFrameSimpleText.insertString(xFrameCursor, "The first line in the newly created text frame.", false); 
            xFrameSimpleText.insertString(xFrameCursor, "\r" + "With this second line the height of the frame raises.", false); 

            //Create a paragraph break 
            xSimpleText.insertControlCharacter(xFrameCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); 

            //Change the CharColor and add a Shadow 
            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(65536)); 
            xPropertySetCursor.setPropertyValue("CharShadowed", new uno.Any(false)); 

            //After we insert our text, we cast our component to XStorable to save it onto the harddisk 
            ((XStorable)xComponent).storeToURL(PathConverter(FileName),          //Convert the file path into a OpenOffice path 
            //no additional arguments 
            new unoidl.com.sun.star.beans.PropertyValue[0]); 
            Console.WriteLine("Your first OpenOffice document is saved!"); 
            Console.ReadLine(); 
        } 
        private static void insertIntoCell(string sCellName, string sText, unoidl.com.sun.star.text.XTextTable xTable) 
        { 
            unoidl.com.sun.star.table.XCell xCell = xTable.getCellByName(sCellName); 

            unoidl.com.sun.star.text.XSimpleText xSimpleTextCell = (unoidl.com.sun.star.text.XSimpleText)xCell; 

            unoidl.com.sun.star.text.XTextCursor xCursor = xSimpleTextCell.createTextCursor(); 

            unoidl.com.sun.star.beans.XPropertySet xPropertySetCursor = (unoidl.com.sun.star.beans.XPropertySet)xCursor; 

            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(0xffffff)); 
            xSimpleTextCell.insertString(xCursor, sText, false); 
        } 
        /// <summary> 
        /// Convert into OO file format 
        /// </summary> 
        /// <param name="file">The file.</param> 
        /// <returns>The converted file</returns> 
        private static string PathConverter(string file) 
        { 
            try 
            { 
                file = file.Replace(@"\", "/"); 
                return "file:///"+file; 
            }catch(System.Exception ex) 
            { 
                throw ex; 
            } 
        } 

        private static void InitOpenOfficeEnvironment() 
        { 
            //from http://blog.nkadesign.com/2008/net-working-with-openoffice-3/ 
            string baseKey = null; 
            // OpenOffice being a 32 bit app, its registry location is different in a 64 bit OS 
            if ((Marshal.SizeOf(typeof(IntPtr)) == 8)) 
            { 
                baseKey = "SOFTWARE\\Wow6432Node\\OpenOffice.org\\"; 
            } 
            else 
            { 
                baseKey = "SOFTWARE\\OpenOffice.org\\"; 
            } 

            // Get the URE directory 
            string key = (baseKey + "Layers\\URE\\1"); 
            RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key); 
            if ((reg == null)) 
            { 
                reg = Registry.LocalMachine.OpenSubKey(key); 
            } 
            string urePath = (string)reg.GetValue("UREINSTALLLOCATION"); 
            reg.Close(); 
            urePath = System.IO.Path.Combine(urePath, "bin"); 
            // Get the UNO Path 
            key = (baseKey + "UNO\\InstallPath"); 
            reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key); 
            if ((reg == null)) 
            { 
                reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(key); 
            } 
            string unoPath = (string)reg.GetValue(null); 
            reg.Close(); 

            string path = null; 
            path = string.Format("{0};{1}", System.Environment.GetEnvironmentVariable("PATH"), urePath); 
            System.Environment.SetEnvironmentVariable("PATH", path); 
            System.Environment.SetEnvironmentVariable("UNO_PATH", unoPath); 
        } 
    } 

    } 
转载地址:http://www.oooforum.org/forum/viewtopic.phtml?t=94558
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
项目使用VS2017打开,.net 2.0下运行。 项目使用的微软官方的插件方法,可以将doc, docx, xls, xlsx, ppt, pptx文件转换为pdf文件,但是需要: 1、用户需要首先安装一个SaveAsPDFandXPS.exe的工具; 2、如果用户是xp系统,则: 2.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 2.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项,然后从office 2007安装包里面安装Microsoft Office Document Imaging(因为2010删除了这个选项,好麻烦~),否则转换失败; 2.3 xp不能安装office 2013/2016; 3、如果用户是win7系统,则: 3.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 3.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win7 + office 2010不需要安装Microsoft Office Document Imaging) 3.3 如果用户安装的是office 2013或2016,则不需要额外选项; 4、如果用户是win10系统,则: 4.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application这个选项,(win10 + office 2007不需要安装Microsoft Office Document Imaging)否则转换失败; 4.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win10 + office 2010不需要安装Microsoft Office Document Imaging) 4.3 如果用户安装的是office 2013或2016,则不需要额外选项; 5、如果用户安装了wps 2016或者wps 2019也可以正常转换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值