简体   繁体   中英

Append predefined style to a Word bookmark with c#

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

  1. By applying the character style "Default Paragraph Font" to the Range or
  2. By using one of the "clear formatting" methods of the Selection object. Which to choose depends on the exact behavior desired. All formatting can be cleared, all direct formatting can be cleared, or the character style can be cleared (which would give the same result as option 1): 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM