I try to set text and a predefined style to a bookmark. Text is fine, but the style is not set. Whats wrong with this source?:
Word.Application word = new Word.Application();
word.Visible = true;
Word.Document doc = word.Documents.Open("bookmark.dotx");
doc.Activate();
Word.Paragraph paragraph = doc.Bookmarks["navigatorHeadlineBookmark"].Range.Paragraphs.Add();
paragraph.Range.Text = "hello headline";
paragraph.Range.set_Style("navigatorHeadline");
//Debug
paragraph.Range.Select(); //selects the expected text (hello headline)
Word.Selection selection = word.Selection;
selection.set_Style("navigatorHeadline"); //style is not set :-(
Summarizing the steps to trouble-shoot that finally led to the answer: 1. First, make sure the bookmark is in the document and contains the correct text/range. 2. Check that the style name is spelled correctly, keeping in mind that Word handles style names as case-sensitive 3. Direct formatting and character styles will override the formatting of a paragraph style.
This last proved to be the reason style formatting was not appearing: the text was formatted with the Hyperlink style. This is a character style, so was overriding the formatting from the style specified in the code.
In this case, the character style must be removed in order to see the formatting from the paragraph style. Programmatically, this can be done EITHER
Selection.ClearCharacterStyle
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.