淺析C#Word文檔替換操作
淺析C#Word文檔替換操作的操作時在文檔中搜索和替換字符串,先在word文檔中標(biāo)記字符串,然后再搜索標(biāo)記字符串并用新的字符串替換標(biāo)記字符串.主要是先選擇整個文檔,然后使用Find的Execute方法查找指定字符串并替換為相應(yīng)字符串.
以下實現(xiàn)淺析C#Word文檔替換操作的方式:
使用文檔(Document )對象的 Content 屬性選擇整個文檔。
- ///﹤summary﹥
- /// 淺析C#Word文檔替換操作,在word 中查找一個字符串直接替換所需要的文本
- /// ﹤/summary﹥
- /// ﹤param name="strOldText"﹥原文本﹤/param﹥
- /// ﹤param name="strNewText"﹥新文本﹤/param﹥
- /// ﹤returns﹥﹤/returns﹥
- public bool Replace(string strOldText,string strNewText)
- {
- this.oDoc.Content.Find.Text = strOldText ;
- object FindText, ReplaceWith, Replace ;//
- object MissingValue = Type.Missing;
- FindText = strOldText ;//要查找的文本
- ReplaceWith = strNewText ;//替換文本
- Replace = Word.WdReplace.wdReplaceAll ;
- /**//*wdReplaceAll - 替換找到的所有項。
- * wdReplaceNone - 不替換找到的任何項。
- * wdReplaceOne - 替換找到的第一項。
- * */
- this.oDoc.Content.Find.ClearFormatting();
- //移除Find的搜索文本和段落格式設(shè)置
- if (this.oDoc.Content.Find.Execute(
- ref FindText,ref MissingValue,
- ref MissingValue,ref MissingValue,
- ref MissingValue,ref MissingValue,
- ref MissingValue,ref MissingValue,ref MissingValue,
- ref ReplaceWith,ref Replace,
- ref MissingValue,ref MissingValue,
- ref MissingValue,ref MissingValue))
- {
- return true ;
- }
- return false ;
- }
說明:其中oDoc是一個word文檔的Document對象.
此外還可以運用Word Application 對象Selection的Find實現(xiàn)淺析C#Word文檔替換操作.
- public bool SearchReplace(string strOldText,string strNewText)
- {
- object replaceAll = Word.WdReplace.wdReplaceAll;
- object missing = Type.Missing;
- //首先清除任何現(xiàn)有的格式設(shè)置選項,然后設(shè)置搜索字符串 strOldText。
- this.oWordApplic.Selection.Find.ClearFormatting();
- oWordApplic.Selection.Find.Text = strOldText;
- oWordApplic.Selection.Find.Replacement.ClearFormatting();
- oWordApplic.Selection.Find.Replacement.Text = strNewText;
- if (oWordApplic.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))
- {
- return true ;
- }
- return false ;
- }
注:oWordApplic是一個Word Application 對象
當(dāng)然也可以使用word文檔的書簽BookMark.使用 Bookmark 的 Range 屬性可將文本插入占位符書簽,以便能夠在以后檢索文本,或替換已包含文本的書簽中的文本。
淺析C#Word文檔替換操作的具體內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)淺析C#Word文檔替換操作有所幫助。
【編輯推薦】