【发布时间】:2017-05-11 14:34:11
【问题描述】:
只是出于兴趣。
带有“Visible: true”的代码正确执行并替换了内容:
Word.Document doc = Utilities.wordEngine.getChangesWordApp.Documents.Open(approvedFileName, ReadOnly: false, Visible:true);
//execute find and replace
Utilities.wordEngine.getChangesWordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
doc.Save();
带有“Visible: false”的代码没有正确执行,内容保持不变:
更新:我在代码周围添加了一个 try catch,它现在确实有效并保存了文档更改,但抛出了异常
Word.Document doc = Utilities.wordEngine.getChangesWordApp.Documents.Open(approvedFileName, ReadOnly: false, Visible:false);
//execute find and replace
try
{
Utilities.wordEngine.getChangesWordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
doc.Save();
}
catch (Exception ex)
{
Trace.TraceInformation(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + " Exception: " + ex.StackTrace);
}
唯一的变化是 Visible:true - 有效,Visible:false 失败。
为什么需要这个?我不想在运行时看到 Word 或文档(幸运的是,在这种情况下,文档在处理过程中实际上并没有显示)
编辑:添加“Utilities.wordEngine”类。
public class wordEngine
{
public static Microsoft.Office.Interop.Word.Application wordClientApp = new Microsoft.Office.Interop.Word.Application();
public static Word.Document sourceWord_Doc;
public static Microsoft.Office.Interop.Word.Application compWordApp = new Microsoft.Office.Interop.Word.Application();
public static Microsoft.Office.Interop.Word.Application massCompWordApp = new Microsoft.Office.Interop.Word.Application();
public static Microsoft.Office.Interop.Word.Application getChangesWordApp = new Microsoft.Office.Interop.Word.Application();
}
更新:我在代码周围添加了一个 try catch: 输出是这样的:
信息:0 : 2017-05-11 16-12-37-657 例外:在 LoadFile.FindAndReplace(字符串批准文件名,字符串开始,字符串 结束,对象 findText) 在 C:\vsCode\wordNameReplacer\wordNameReplacer\Replacer\LoadWordFile.xaml.cs:line 685
异常内容的屏幕截图。我找不到任何未设置的对象(除非 Word 需要一些缺少的参数对象进行搜索和替换)
【问题讨论】:
-
“不工作”和“失败”不是恰当的问题描述。
-
对不起,汉斯,不太确定你想要什么?问题标题加上不工作/工作是一个合理的解释,不是吗?本质上“可见:真”将允许搜索和替换运行,“可见:假”失败
-
好的,运行调试异常给出:{“对象引用未设置为对象的实例。”}
标签: c# ms-word office-interop