阅读背景:

C#_Word_通过书签替换文字、图片等等

来源:互联网 

通过Word书签调换文字,图片 

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param> Word地址
        /// <param name="oldStr"></param> 书签
        /// <param name="newStr"></param>  新文字或图片地址
        /// <param name="type"></param>  类型
        public void testimg(string filePath,string oldStr,string newStr,string type)
        {
            

            object Nothing = System.Reflection.Missing.Value;
            //创立一个名为wordApp的组件对象
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            //word文档地位
            object filename = filePath;

            //定义该插入图片是不是为外部连接
            object linkToFile = true;

            //定义插入图片是不是随word文档一起保留
            object saveWithDocument = true;

            //打开word文档
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing,
               ref Nothing, ref Nothing, ref Nothing, ref Nothing,
               ref Nothing, ref Nothing, ref Nothing, ref Nothing,
               ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            try
            {
                //书签
                object bookMark = oldStr;
                //图片或文字
                string replacePic = newStr;
                //书签是不是存在
                if (doc.Bookmarks.Exists(Convert.ToString(bookMark)) == true)
                {
                    //查找书签
                    doc.Bookmarks.get_Item(ref bookMark).Select();
                    //是图片还是文字
                    if (type.Equals("img"))
                    {
                        //设置图片地位
                        wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                        //在书签的地位添加图片
                        InlineShape inlineShape = wordApp.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref Nothing);
                        wordApp.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref Nothing);
                        //设置图片大小
                        inlineShape.Width = 300;
                        inlineShape.Height = 300;
                    }
                    else 
                    {
                        //文字就直接调换
                        wordApp.Selection.Text = replacePic;
                    }

                    doc.Save();
                    doc.Close(ref Nothing, ref Nothing, ref Nothing);
                    wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
                }
                else
                {
                    //word文档中不存在该书签,关闭文档
                    doc.Close(ref Nothing, ref Nothing, ref Nothing);
                }
            }
            catch
            {
            }
        }        /// <summary>
       



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: