目前我正在尝试构建一个工具,该工具将打开Microsoft Word文档文件并更新文档中的所有字段。这里是主代码:无法使用.NET更新Microsoft Word文档字段
using Microsoft.Office.Interop.Word;
public class clsDocumentFieldUpdateTool
{
private static Microsoft.Office.Interop.Word.Application wordApp = null;
private static Microsoft.Office.Interop.Word.Document oDoc = null;
private static object missing = null;
private static object readOnly = false;
private static object visible = true;
public static void OpenDocument(string docFileNameWithPath)
{
wordApp = new Microsoft.Office.Interop.Word.Application();
missing = System.Reflection.Missing.Value;
object fileToOpen = docFileNameWithPath;
try
{
oDoc = wordApp.Documents.Open(ref fileToOpen, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref visible, ref visible, ref missing, ref missing, ref missing);
}
catch (Exception excOpenFile)
{
MessageBox.Show(excOpenFile.Message + System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + " - " + excOpenFile.StackTrace);
}
}
private static void Update(string file)
{
object nothing = System.Reflection.Missing.Value; // our 'void' value
object filename = file; // our word template
object notTrue = false; // our boolean false
try
{
//
// now we want to load the template and check how many fields there are to replace
//
wordApp.Visible = true;
oDoc = wordApp.Documents.Add(// load the template into a document workspace
ref filename, // and reference it through our myWordDoc
ref missing,
ref missing,
ref missing);
dynamic properties = oDoc.BuiltInDocumentProperties;
// count how many fields we have to update
int fields = oDoc.Fields.Count;
foreach (Field myField in oDoc.Fields)
{
myField.Select();
myField.Update();
}
oDoc.Save();
oDoc.Close(ref notTrue, ref missing, ref missing);
wordApp.Application.Quit( ref notTrue,
ref missing,
ref missing);
}
catch (Exception excException)
{
MessageBox.Show(excOpenFile.Message + System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + " - " + excException.StackTrace);
}
}
public static void UpdateDocumentFieldsInFile()
{
string strFile = @"L:\admin\11ZG-0401\11-SWDev\Testing Field Updates (from Document Properties).docx";
OpenDocument(strFile);
Update(strFile);
}
}
其中主函数调用UpdateDocumentFieldsInFile()。当我单步执行代码时,它会打开文件并更新它,但在程序退出并手动重新打开文件后,这些字段尚未更新。有没有人有任何建议如何解决这个问题? TIA。
不显示`excException.ToString()`给你足够的信息吗? – 2011-12-16 22:38:52