• 使用C#替换Word文档里的文字和图片


    基本思路


    替换文字:使用Microsoft.Office.Interop.Word接口中的Find属性:

     Object missing = Missing.Value;
                object replaceAll = WdReplace.wdReplaceAll;
    
                _application.Selection.Find.ClearFormatting();
                _application.Selection.Find.Text = origialString;
    
                _application.Selection.Find.Replacement.ClearFormatting();
                _application.Selection.Find.Replacement.Text = destinationString;
    
                _application.Selection.Find.Execute(
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);

    其中,_application是Microsoft.Office.Interop.Word.Application类型的变量,_application.Selection.Find.Text = origialString; 用来指定要被替换的文字,_application.Selection.Find.Replacement.Text = destinationString;用来指定替换后的文字。在实践过程中,发现了两个问题需要解决;问题1,当替换后的文字长度超过255个时,该方法执行时会出现异常;问题2:无法替换文本框中的字符,为此,将方法修改如下:

    //用模板字符替换原字符
            private void ReplaceString(string origialString, string destinationString)
            {
                #region 如果目标字符串长度大于255,则分成小于255的若干多分别进行替换
                /*
                 * 例如:destinationString的长度是300;
                 * 第一步:将origialString替换为“$$$1$”和“$$$2$”;
                 * 第二步:将destinationString分解为两个字符串,第一个字符串长度255,第二个字符串长度300-255=45;
                 * 第三步:用第一个字符串替换“$$$1$”,用第二个字符串替换“$$$2$”
                 */
                if (destinationString.Length > 255)
                {
                    int count = destinationString.Length / 255 + ((destinationString.Length % 255) == 0 ? 0 : 1);
                    List<string> origianlStringList = new List<string>();
                    List<string> destinationStringList = new List<string>();
                    for (int i = 0; i < count; i++)
                    {
                        origianlStringList.Add("$$$" + i.ToString() + "$");
    
                        int length;//每小段的长度
                        if (i != count - 1)
                        {
                            length = 255;
                        }
                        else
                        {
                            length = destinationString.Length % 255;
                        }
                        destinationStringList.Add(destinationString.Substring(i * 255, length));
                    }
                    string origianlStringListTotalString = string.Empty;
                    for (int i = 0; i < count; i++)
                    {
                        origianlStringListTotalString += origianlStringList[i];
                    }
                    this.ReplaceString(origialString, origianlStringListTotalString);
                    for (int i = 0; i < count; i++)
                    {
                        this.ReplaceString(origianlStringList[i], destinationStringList[i]);
                    }
                    return;
                }
    
                #endregion
    
                Object missing = Missing.Value;
                object replaceAll = WdReplace.wdReplaceAll;
    
                _application.Selection.Find.ClearFormatting();
                _application.Selection.Find.Text = origialString;
    
                _application.Selection.Find.Replacement.ClearFormatting();
                _application.Selection.Find.Replacement.Text = destinationString;
    
                _application.Selection.Find.Execute(
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);
                //
                //替换在文本框中的文字
                //
                StoryRanges ranges = _application.ActiveDocument.StoryRanges;
                foreach (Range item in ranges)
                {
                    if (WdStoryType.wdTextFrameStory == item.StoryType)
                    {
                        Range range = item;
                        while (range != null)
                        {
                            range.Find.ClearFormatting();
                            range.Find.Text = origialString;
                            range.Find.Replacement.Text = destinationString;
                            range.Find.Execute(
                        ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
                            range = range.NextStoryRange;
                        }
                        break;
                    }
                }
            }
        }

    替换图片:在要被替换的图片前加入书签,替换时遍历书签,并读取书签后面的图片,将给定图片设置为和原始图片一样大小,并放在书签后面替换原有图片:

    /// <summary>
    /// 要设置图片的名称(路径+图片名称)
    /// </summary>
    /// <param name="index">书签名称</param>
    /// <returns>图片路径</returns>
    public string this[string index]
    {
        set
        {
            if (File.Exists(value))
            {
                foreach (Bookmark item in _application.ActiveDocument.Bookmarks)
                {
                    if (item.Name == index)
                    {
                        item.End += 1;
                        item.Select();
                        object missing = Missing.Value;
                        if (_application.Selection.InlineShapes.Count > 0)
                        {
                            float width = _application.Selection.InlineShapes[0].Width;
                            float height = _application.Selection.InlineShapes[0].Height;
                            try
                            {
                                InlineShape shape = _application.Selection.InlineShapes.AddPicture(value, ref missing, ref missing, ref missing);
                                shape.Width = width;
                                shape.Height = height;
                            }
                            catch (Exception)
                            {
                                throw new Exception("无法插入图片!");
                            }
                        }
                    }
                }
            }
        }
    }
    其中,索引Index为书签名,索引值为新图片的路径

  • 相关阅读:
    获取动态类型变量的属性值
    C#项目实例中读取并修改App.config文件
    c#防止多次运行代码收集
    c# winform 关闭窗体时同时结束线程实现思路
    C# App.config 自定义 配置节 报错“配置系统未能初始化” 解决方法
    在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke 解决办法
    用 C# 在 Windows 7 中写注册表想到的
    this指针
    UML类图,用例图,时序图
    常见的框架模式:MVC MVP MTV等
  • 原文地址:https://www.cnblogs.com/zzy0471/p/1903629.html
Copyright © 2020-2023  润新知