我正在尝试以编程方式替换Word文档中书签的文本。我可以在书签上找到文本(我正在使用只有一个书签的测试文档),并将其打印出来进行调试 - 但似乎无法设置文本的值。如何替换书签上的文字?
WordprocessingDocument wordprocessingDocument=WordprocessingDocument.Open(filepath, true);
foreach (BookmarkStart bookmark in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>())
{
System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.Parent.InnerText);
/* Below line does not work */
bookmark.Parent.InnerText = "My Replacement Text"
}
答案 0 :(得分:0)
开始所有书签
public List<WP.BookmarkStart> GetAllBookmarks ()
{
var bmk = _workspace.MainDocumentPart.RootElement.Descendants<WP.BookmarkStart>().ToList();
return bmk;
}
迭代所有书签
foreach (var bookmark in bookmarks)
{
string modifiedString = GetModifiedString();
ReplaceBookmarkText(bookmark, modifiedString);
}
替换书签文字
public void ReplaceBookmarkText(WP.BookmarkStart bookmark, string newText)
{
try
{
var bmkText = bookmark.NextSibling<WP.Run>();
if (bmkText != null)
{
bmkText.GetFirstChild<WP.Text>().Text = newText;
wordprocessingDocument.MainDocumentPart.Document.Save();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
}
WP
using WP = DocumentFormat.OpenXml.Wordprocessing;