OLE,Object Linking and Embedding,即对象连接与嵌入。我们在设计程序时,OLE可以用来创建复合文档,把文字、声音、图像、表格、应用程序等类型的信息组合在一起,在Word中,我们可以通过OLE来实现以上要素信息的组合。下面的示例中将介绍如何通过C# 来操作Word中的OLE,示例内容包含以下要点:

  • 插入OLE到Word
  • 编辑Word中的OLE
  • 读取Word中的OLE

 

使用工具

:下载安装该类库,在编辑代码时,注意在程序中添加引用Spire.Doc.dll(dll文件可在安装路径下的Bin文件夹中获取)

C# 操作Word 中的OLE——插入、编辑、读取 OLE

示例代码(供参考)

【示例1】插入OLE到Word

步骤 1 :添加using指令

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

步骤 2 :创建文档

//实例化一个Document类对象
Document doc = new Document();
//向文档中添加一个Section对象,并添加段落
Section sec = doc.AddSection();
Paragraph p = sec.AddParagraph();

步骤 3 :加载图片

//实例化一个DocPicture类对象,加载图片
DocPicture picture = new DocPicture(doc);
Image image = Image.FromFile(@"chart1.png");
picture.LoadImage(image);

步骤 4 :插入OLE

//在文档中插入一个工作表, OleLinkType 枚举值控制该OLE是链接还是嵌入
DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Link);
//DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Embed);

步骤 5 :保存文档

//保存并打开文档
doc.SaveToFile("添加OLE.docx");
System.Diagnostics.Process.Start("添加OLE.docx");

完成代码后,调试运行程序,生成文档。

测试结果,如下图所示:

C# 操作Word 中的OLE——插入、编辑、读取 OLE

全部代码:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace InsertOLE_Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化一个Document类对象
            Document doc = new Document();
            //向文档中添加一个Section对象,并添加段落
            Section sec = doc.AddSection();
            Paragraph p = sec.AddParagraph();

            //实例化一个DocPicture类对象,加载图片
            DocPicture picture = new DocPicture(doc);
            Image image = Image.FromFile(@"chart1.png");
            picture.LoadImage(image);

            //在文档中插入一个工作表, OleLinkType 枚举值控制该OLE是链接还是嵌入         
            DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Link);
            //DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Embed);

            //保存并打开文档
            doc.SaveToFile("添加OLE.docx");
            System.Diagnostics.Process.Start("添加OLE.docx");
        }
    }
}
View Code

相关文章: