这是我正在使用的代码。它确实有效。
我有两种不同的方式来编辑现有的Microsoft Word书签,它们都有效。
但他们都把书签变成了文字。
是否可以将它们保存为书签形式?
private void ___button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Document|*.docx";
dialog.ShowDialog();
path = dialog.FileName;
Word.Application app = null;
Process[] ps = Process.GetProcessesByName("WINWORD");
if (ps.Length > 1)
{
app = (Word.Application)Marshal.GetActiveObject("Word.Application");
}
else
{
app = new Word.Application();
}
object missing = Type.Missing;
Word.Document doc = app.Documents.Open(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing);
// one way to edit bookmarks...
object oBookMark = "FirstName";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox1.Text;
// another way...
doc.Bookmarks["LastName"].Range.Text = textBox2.Text;
doc.Bookmarks["position"].Range.Text = textBox3.Text;
// both of these ways work, but they both turn the bookmark into text
//clears the textboxes
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
//show the document
app.Visible = true;
// save the document
app.Documents.Save(ref missing, ref missing);
// close the application
app.Application.Quit(ref missing, ref missing, ref missing);
// release objects from memory?
Marshal.ReleaseComObject(app);
}
我在这里查看了MSDN上的差异(http://msdn.microsoft.com/en-us/library/vstudio/5ykkex00.aspx),它说使用Bookmark,text vs range.Text。 但由于某些原因,Bookmark.Text不起作用。
*修改
所以我已经弄明白了。
我刚换了:
object oBookMark = "FirstName";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox1.Text;
使用:
object oBookMark = "FirstName";
doc.FormFields.get_Item(ref oBookMark).Result = textBox1.Text;