新增樣式文字
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;

// Load docx
WordDocument doc = new WordDocument("document.docx");

// Configure text
Run textRun = new Run(new TextContent("Add text using IronWord"));
textRun.Style = new TextStyle()
{
	FontSize = 72,
	TextFont = new Font()
	{
		FontFamily = "Caveat"
	},
	Color = IronWord.Models.Color.Red,
	IsBold = true,
	IsItalic = true,
	Underline = new Underline(),
	Strike = StrikeValue.Strike,
};

Paragraph paragraph = new Paragraph();

// Add text
paragraph.AddChild(textRun);

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("save_document.docx");
NuGet 下載
PM > Install-Package IronWord
新增樣式文字

新增樣式文字

IronWord 中的「新增樣式文字」功能可讓開發人員在 DOCX 文件中新增內容時套用各種文字樣式選項。 它提供對文本外觀的精細控制,例如指定字體系列、大小、顏色和樣式屬性,如bold、italic、underline和strike-through。 通過創建一個包含TextContent的Run對象並將TextStyle分配給Run,開發者可以定制文本元素在文件中的呈現方式,確保提供定制的外觀和感受。

此功能可用於動態產生專業格式的文檔,例如報告或信函,其中特定部分需要不同的樣式。 TextStyle類別能夠輕鬆地操作這些屬性,允許在同一個文件中進行簡單和複雜的樣式設計。

重點

  1. 創建樣式化的運行:
    • 創建一個Run對象,包含所需文本的TextContent。
    • 將TextStyle對象分配給Run的Style屬性以套用格式。 FontSize
  2. 配置TextStyle:
    • TextStyle:在TextStyle層級設置(不在Font內部)以指定文本大小。
    • TextFont:包含字體屬性,包括用於字體選擇的fontFamily。 FontFamily
    • Color:使用color指定文本顏色。 IronWord.Models.Color
    • bold和italic:用於粗體和斜體格式的布林屬性。 IsBold
    • underline:為文本添加下劃線樣式。 Underline
    • strike-through:使用StrikeValue枚舉套用刪除線格式。 Strike
  3. 新增至文件:
    • 使用AddChild將帶樣式的Run添加到Paragraph。
    • 然後使用AddParagraph將段落新增至文件。

程式碼說明

此程式碼示範如何使用 IronWord 在 DOCX 文件中建立和設定文字樣式。 它從“document.docx”中載入現有的WordDocument物件開始。 創建一個Run對象,包含字符串"Styled text example"的TextContent,並將TextStyle套用到Run以配置文本的外觀。

TextStyle包括設定在TextStyle層級(不在Font內)的字體大小、通過fontFamily配置的字體系列、TextFont文本color,以及bold格式。 這些設定用於自訂文字在最終文件中的顯示方式。

在Run被設計後,AddChild方法將Run對象添加到文件的段落中。 此方法會將樣式化的內容以適當的格式插入 Word 文件中。 最後,SaveAs方法被調用以將文件匯出為“save_document.docx”。 在最終產生的 Word 文件中,插入的文字將按照指定的樣式進行格式化,並在輸出檔案中保留所有字體和格式屬性。

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

準備好開始了嗎?

NuGet 下載次數 62,392版本:2026.11剛剛發布