添加樣式文本

IronWord 中的"新增樣式文字"功能可讓開發人員在 DOCX 文件中新增內容時套用各種文字樣式選項。 它可以對文字外觀進行精細控制,例如指定字體系列、大小、顏色以及粗體、斜體、底線和刪除線等樣式屬性。 透過建立一個包含 TextContentRun 物件,並將 TextStyle 指派給 Run,開發人員可以自訂文件中個別文字元素的呈現方式,確保呈現出客製化的外觀與風格。

此功能可用於動態產生專業格式的文檔,例如報告或信函,其中特定部分需要不同的樣式。 TextStyle 類別可輕鬆操作這些屬性,讓您在同一份文件中同時實現簡單與複雜的樣式設定。

重點

  1. 建立樣式化執行程序

    • A Run object is created containing TextContent with the desired text.
    • The Style property of the Run is assigned a TextStyle object to apply formatting.
  2. 設定 TextStyle

    • FontSize: Set at the TextStyle level (not inside Font) to specify text size.
    • TextFont: Contains font properties including FontFamily for font selection.
    • Color: Specifies the text color using IronWord.Models.Color.
    • IsBold and IsItalic: Boolean properties for bold and italic formatting.
    • Underline: Adds underline styling to the text.
    • Strike: Applies strikethrough formatting using StrikeValue enum.
  3. 新增至文件
    • Use AddChild to add the styled Run to a Paragraph.
    • The paragraph is then added to the document with AddParagraph.

程式碼解釋

此程式碼示範如何使用 IronWord 在 DOCX 文件中建立和設定文字樣式。 It begins by initializing a new WordDocument object, representing the document to be generated. A Run object is created containing TextContent with the string "Styled text example" and a TextStyle is applied to the Run to configure the appearance of the text.

The TextStyle includes settings for font size set at the TextStyle level (not inside Font), font family configured via TextFont, text color, and bold formatting. 這些設定用於自訂文字在最終文件中的顯示方式。

After the Run is styled, the AddChild method adds the Run object to a paragraph in the document. 此方法會將樣式化的內容以適當的格式插入 Word 文件中。 Finally, the SaveAs method is called to export the document as "styled_document.docx". 在最終產生的 Word 文件中,插入的文字將按照指定的樣式進行格式化,並在輸出檔案中保留所有字體和格式屬性。

瀏覽文件元素教程,以取得更多樣式技巧

準備好開始了嗎?
Nuget 下載 36,374 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronWord
執行範例 觀看您的資料變成 Word doc。