C#替换Word中的文本内容(亲测)

1

   Word文档文本替换时长度不能超过255个字符,不能一次性替换,本方法通过循环替换,达到替换超过255字符的目的。

复制代码
/// <summary>
/// 替换word中的文字
/// </summary>
/// <param name="filePath">文件的路径</param>
/// <param name="datas">包含待替换字符串和替换字符串的集合</param>
/// <returns>true 替换成功;false 替换失败</returns>
public static bool WordReplace(string filePath, Dictionary<string, string> datas)
{
    bool result = false;
    Microsoft.Office.Interop.Word._Application app = null;
    Microsoft.Office.Interop.Word._Document doc = null;
 
    object nullobj = Type.Missing;
    object file = filePath;
 
    try
    {
        app = new Microsoft.Office.Interop.Word.Application();//new Microsoft.Office.Interop.Word.ApplicationClass();
 
        doc = app.Documents.Open(
        ref file, ref nullobj, ref nullobj,
        ref nullobj, ref nullobj, ref nullobj,
        ref nullobj, ref nullobj, ref nullobj,
        ref nullobj, ref nullobj, ref nullobj,
        ref nullobj, ref nullobj, ref nullobj, ref nullobj) as Microsoft.Office.Interop.Word._Document;
 
        //app.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 2;//首行缩进的长度
 
        object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
 
        foreach (var item in datas)
        {
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            string oldStr = item.Key;//需要被替换的文本
            string newStr = item.Value; //替换文本 
 
            if (newStr == null)
            {
                newStr = "";
            }
            int newStrLength = newStr.Length;
            if (newStrLength <= 255) // 长度未超过255时,直接替换
            {
                app.Selection.Find.Text = oldStr;
                app.Selection.Find.Replacement.Text = newStr;
 
                app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                           ref nullobj, ref nullobj, ref nullobj,
                                           ref nullobj, ref nullobj, ref nullobj,
                                           ref nullobj, ref objReplace, ref nullobj,
                                           ref nullobj, ref nullobj, ref nullobj);
                continue;
            }
            //word文本替换长度不能超过255
            int hasSubLength = 0;
            int itemLength = 255 - oldStr.Length;
            while (true)
            {
                string itemStr = "";
                int subLength = 0;
                if (newStrLength - hasSubLength <=255)  // 剩余的内容不超过255,直接替换
                {
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();
 
                    app.Selection.Find.Text = oldStr;
                    app.Selection.Find.Replacement.Text = newStr.Substring(hasSubLength, newStrLength - hasSubLength);
 
                    app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                                ref nullobj, ref nullobj, ref nullobj,
                                                ref nullobj, ref nullobj, ref nullobj,
                                                ref nullobj, ref objReplace, ref nullobj,
                                                ref nullobj, ref nullobj, ref nullobj);
                    break; // 结束循环
                }
 
                // 由于Word中换行为“^p”两个字符不能分割
                // 如果分割位置将换行符分开了,则本次少替换一个字符
                if (newStr.Substring(hasSubLength, itemLength).EndsWith("^") &&
                    newStr.Substring(hasSubLength, itemLength + 1).EndsWith("p"))
                {
                    subLength = itemLength - 1;
                }
                else
                {
                    subLength = itemLength;
                }
 
                itemStr = newStr.Substring(hasSubLength, subLength) + oldStr;
 
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();
 
                app.Selection.Find.Text = oldStr;
                app.Selection.Find.Replacement.Text = itemStr;
 
                app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                            ref nullobj, ref nullobj, ref nullobj,
                                            ref nullobj, ref nullobj, ref nullobj,
                                            ref nullobj, ref objReplace, ref nullobj,
                                            ref nullobj, ref nullobj, ref nullobj);
                hasSubLength += subLength;
            }
        }
        //保存
        doc.Save();
        result = true;
    }
    catch
    {
        result = false;
    }
    finally
    {
        if (doc != null)
        {
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            doc = null;
        }
        if (app != null)
        {
            app.Quit(ref nullobj, ref nullobj, ref nullobj);
            app = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    return result;
}
复制代码

每次替换的长度为255减去待替换文本长度;

另外,Word中的换行符是“^p”,如果替换文本中有换行符,需要在循环替换时检查是否将该字符切割了,如果切割了,则少截取一个字符;

---转自fengxingke

2

3

posted on   8888888888888  阅读(122)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

Live2D
点击右上角即可分享
微信分享提示