C#替换Word中的文本内容

来源:互联网 发布:python黑帽子中文下载 编辑:程序博客网 时间:2024/05/01 19:34

        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”,如果替换文本中有换行符,需要在循环替换时检查是否将该字符切割了,如果切割了,则少截取一个字符;

原创粉丝点击