現在、Microsoft Word文書ファイルを開き、文書内のすべてのフィールドを更新するツールを作成しようとしています。メインコードは次のとおりです。は、Microsoft Word文書フィールドを.NETを使用して更新できません
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);
}
}
ここで、main関数はUpdateDocumentFieldsInFile()を呼び出します。コードをステップ実行すると、ファイルが開き、更新されますが、プログラムが終了してファイルを手動で再度開くと、フィールドは更新されません。誰もこれを解決する方法に関する提案はありますか? TIA。
'excException.ToString()'は十分な情報を表示していませんか? –