【C#】 Word 替换操作

使用Microsoft.Office.Interop.Word操作Word

using System;
using System.Collections.Generic;
using Word = Microsoft.Office.Interop.Word;
namespace Com.FToolsforExcel.Processor.WordProcessDef { public class WordReplacer { private Word.Application app; private Word.Document document; private List<ReplaceStr> replaceStrs; private bool mtchWildcards; public WordReplacer( List<ReplaceStr> replaceStrs,bool matchWildcards) { this.replaceStrs = replaceStrs; this.mtchWildcards = matchWildcards; } private bool GetDocument(string docPath, out Word.Document document) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(docPath); if (fileInfo.Extension.Contains("doc")) { try { this.app = new Word.Application(); this.app.Visible = false; this.app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; document = this.app.Documents.Open(docPath); return true; } catch (Exception) { this.Close(); document = null; this.app = null; return false; } } else { document = null; return false; } } private void Close() { this.document.Close(); this.app.Quit(); this.document = null; this.app = null; } public ProcessingResultEnum Replace(string docPath, string usless = "") { if (this.replaceStrs == null) { return ProcessingResultEnum.ParamErr; } if (this.GetDocument(docPath, out this.document)) { try { foreach (var item in replaceStrs) { Word.Find find = this.document.Content.Find; find.MatchWildcards = this.mtchWildcards; find.Text = item.Old; find.Replacement.Text = item.New; find.Execute(Replace: Word.WdReplace.wdReplaceAll, Forward: true, Wrap: Word.WdFindWrap.wdFindContinue); } this.Close(); return ProcessingResultEnum.Successful; } catch (Exception) { this.Close(); return ProcessingResultEnum.UnknownErr; } } else return ProcessingResultEnum.OpenErr; } } public struct ReplaceStr { public string Old; public string New; public ReplaceStr(string oldStr, string newStr) { Old = oldStr; New = newStr; } } }

 

posted @ 2022-05-04 12:06  yzhyingcool  阅读(594)  评论(0编辑  收藏  举报