C# 修改、编辑Word中的OLE对象

2025-11-05 04:02:14

1、在E-iceblue官网或者Nuget网站上下载 Spire.Doc for .NET的安装包后,注意在编辑代码时,添加引用Spire.Doc.dll到程序。dll文件可在安装路径下的Bin文件夹中获取。

C# 修改、编辑Word中的OLE对象

1、测试文档 如下:

C# 修改、编辑Word中的OLE对象

2、using Spire.Doc;

using Spire.Doc.Documents;

using Spire.Doc.Fields;

using System.Drawing;

using System.IO;

namespace EditOLE_Doc

{

    class Program

    {

        static void Main(string[] args)

        {

            //实例化一个Document对象,加载含有OLE的Word文档

            Document doc = new Document();

            doc.LoadFromFile("test.docx");

            //获取第一个Section

            Section sec = doc.Sections[0];

            //遍历这个Section中的所有子元素,找到段落下的OLE对象

            foreach (DocumentObject obj in sec.Body.ChildObjects)

            {

                if (obj is Paragraph)

                {

                    Paragraph par = obj as Paragraph;

                    foreach (DocumentObject paraObj in par.ChildObjects)

                    {

                        //找到OLE对象,根据类型来进行更改操作

                        if (paraObj.DocumentObjectType == DocumentObjectType.OleObject)

                        {

                            DocOleObject Ole = paraObj as DocOleObject;

                            //如果是链接, 修改对象的链接路径

                            if (Ole.LinkType == OleLinkType.Link)

                            {

                                //同时还要手动去更改OLE的图片

                                DocPicture pic = Ole.OlePicture;

                                pic.LoadImage(Image.FromFile("Img.png"));

                                Ole.LinkPath = @"sample.docx";

                            }

                            //如果是嵌入,更改数据即可

                            byte[] bys = File.ReadAllBytes(@"sample.docx");

                            if (Ole.LinkType == OleLinkType.Embed)

                            {

                                DocPicture pic = new DocPicture(doc);

                                pic.LoadImage(Image.FromFile(@"Img.png"));

                                Ole.ObjectType = "Word.Document.12";

                                Ole.SetOlePicture(pic);

                                Ole.SetNativeData(bys);

                            }

                        }

                    }

                }

            }

            //保存修改后的文档,并打开

            doc.SaveToFile("修改OLE.docx", Spire.Doc.FileFormat.Docx2010);

            System.Diagnostics.Process.Start("修改OLE.docx");

        }

    }

}

3、调试运行程序后,生成文档。打开文档时,生成的文档中原有的插入OLE的图片和链接的文档都已经更改了,如下所示:

C# 修改、编辑Word中的OLE对象

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢