簡體   English   中英

通過.NET自動化在Word文檔中搜索和替換

[英]search and replace in Word documents via .NET automation

我有一個較舊的項目,我想打開一個Word文檔並執行搜索和替換。 它之前我有較舊的Visual Studio和Office,但現在我在VS 2012中遇到了問題(安裝了Office 2013)。

我引用“Microsoft Word 15.0對象庫”COM參考,我得到3個dll文件:

Microsoft.Office.Core
Microsoft.Office.Interop.Word
VBIDE

我的最小測試代碼:

using Word = Microsoft.Office.Interop.Word;

...

object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.doc");

Word.Application wordApp = new Word.Application { Visible = true };                        

Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: true, Visible: true);

aDoc.Activate();

Word.Find fnd = wordApp.ActiveWindow.Selection.Find;

fnd.ClearFormatting();
fnd.Replacement.ClearFormatting();
fnd.Forward = true;
fnd.Wrap = Word.WdFindWrap.wdFindContinue;                             

fnd.Text = "aaa";
fnd.Replacement.Text = "bbb";

fnd.Execute(Replace: Word.WdReplace.wdReplaceAll);

此代碼運行並打開文檔,但隨后會發生此異常:

System.Runtime.InteropServices.COMException was unhandled
HelpLink=wdmain11.chm#37373
HResult=-2146823683
Message=This command is not available.
Source=Microsoft Word
ErrorCode=-2146823683
StackTrace:
   at Microsoft.Office.Interop.Word.Find.Execute(Object& FindText, Object& MatchCase,   Object& MatchWholeWord, Object& MatchWildcards, Object& MatchSoundsLike, Object& MatchAllWordForms, Object& Forward, Object& Wrap, Object& Format, Object& ReplaceWith, Object& Replace, Object& MatchKashida, Object& MatchDiacritics, Object& MatchAlefHamza, Object& MatchControl)
   at WordTest.MainForm.btnLaunchWord_Click(Object sender, EventArgs e) in c:\Work\Repos\WordTest\WordTest\Form1.cs:line 38

到底是怎么回事? 我還有一個問題:如果我使用V10.0的Interop程序集(我想我的Office 2013附帶),相同的代碼是否可以在安裝了以前版本的Word的機器上運行 - 讓我們說Office 2010?

在替換文檔中的文本之前,請在此行中將ReadOnly更改為false:

Word.Document aDoc = wordApp.Documents.Open(
    ref fileName, ReadOnly: true, Visible: true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM