如何在 C# 中處理文件元素

C# Document Element Tutorial

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWord 是一款強大的 Word 文件程式庫,旨在協助 .NET C# 開發人員將建立、讀取及編輯 Word 和 DOCX 文件的功能整合至其應用程式中。 在 WORD 文件的語境中,文件元素是構成內容的基本組件。

快速入門:建立樣式化 TextRun 並嵌入圖片

以下說明如何使用 IronWord 添加豐富內容——在文件中結合格式化文字與嵌入圖片。 此範例展示了 Run 包裹模式在格式化文字中的應用。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronWord

    PM > Install-Package IronWord
  2. 請複製並執行此程式碼片段。

    using IronWord;
    using IronWord.Models;
    
    // Create document
    WordDocument doc = new WordDocument();
    
    // Create styled Run
    Run textRun = new Run(new TextContent("Hello IronWord!"));
    textRun.Style = new TextStyle() { IsBold = true, Color = Color.Blue };
    
    // Create paragraph and add Run
    Paragraph paragraph = new Paragraph();
    paragraph.AddChild(textRun);
    paragraph.AddImage(new ImageContent("pic.png"));
    
    // Add to document and save
    doc.AddParagraph(paragraph);
    doc.SaveAs("output.docx");
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronWord

    arrow pointer

目錄

關鍵概念

文件層級結構

IronWord 採用結構化的文件層級:Document → Paragraph → Run → TextContent。 理解此層級結構對於處理格式化文字至關重要:

  • WordDocument:代表整個文件的頂層容器
  • Paragraph:文件中的內容區塊
  • Run:一個包含 TextContent 的封裝物件,可套用樣式
  • TextContent:實際文字字串

在段落中添加內容

IronWord 提供兩種向段落中添加內容的方法:

  • AddText(TextContent):用於未格式化的純文字。 將 TextContent 直接加入段落中。
  • AddChild(Run):用於格式化文字。 在段落中新增一個 Run 物件(該物件包覆 TextContent 並包含樣式設定)。

當您需要套用字型大小、顏色或粗體等格式時,請建立一個 Run 物件,將 TextStyle 指派給 Run,並使用 AddChild 將其加入段落中。

新增文字區塊

文字內容

using Split 方法,根據指定的分隔符號將文本段落分割成多個較小的文本段落。 這使得能夠對文件內的文字資訊進行組織與處理。

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-text-content.cs
using IronWord;
using IronWord.Models;

WordDocument doc = new WordDocument();

// Add text
TextContent addText = new TextContent("Add text using IronWord");
doc.AddParagraph(new Paragraph(addText));

// Append text
TextContent appendText = new TextContent("The first text.");
appendText.Append(new TextContent("The second text."));
doc.AddParagraph(new Paragraph(appendText));

// Split text
TextContent splitText = new TextContent("Use split to split the sentence.");
splitText.Split(" ");
doc.AddParagraph(new Paragraph(splitText));

// Export docx
doc.SaveAs("textrun.docx");
Imports IronWord
Imports IronWord.Models

Private doc As New WordDocument()

' Add text
Private addText As New TextContent("Add text using IronWord")
doc.AddParagraph(New Paragraph(addText))

' Append text
Dim appendText As New TextContent("The first text.")
appendText.Append(New TextContent("The second text."))
doc.AddParagraph(New Paragraph(appendText))

' Split text
Dim splitText As New TextContent("Use split to split the sentence.")
splitText.Split(" ")
doc.AddParagraph(New Paragraph(splitText))

' Export docx
doc.SaveAs("textrun.docx")
$vbLabelText   $csharpLabel

設定樣式

設定文字樣式時,需使用 Run 包覆模式。 建立一個包含 TextContentRun 物件,然後將 TextStyle 指派給 Run(而非 TextContent)。 TextStyle 讓您能夠定義視覺屬性,例如 FontSize、顏色、粗體、斜體、刪除線、底線、上標及下標。

請注意,FontSize 是在 TextStyle 層級進行設定,而 FontFamily 則設定於 TextFont 屬性之中。 格式設定完成後,請使用 AddChildRun 加入段落中。 此文件遵循以下層級結構:Document → Paragraph → Run → TextContent

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-set-styling.cs
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 = 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");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums

' Load docx
Dim doc As New WordDocument("document.docx")

' Configure text
Dim textRun As New Run(New TextContent("Add text using IronWord"))
textRun.Style = New TextStyle() With {
    .FontSize = 72,
    .TextFont = New Font() With {
        .FontFamily = "Caveat"
    },
    .Color = Color.Red,
    .IsBold = True,
    .IsItalic = True,
    .Underline = New Underline(),
    .Strike = StrikeValue.Strike
}

Dim paragraph As New Paragraph()

' Add text
paragraph.AddChild(textRun)

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("save_document.docx")
$vbLabelText   $csharpLabel

取得文字填充顏色

除了設定樣式外,IronWord 還提供一種方法,讓您從現有文件中取得 RGBA 顏色值,以確保整體樣式的一致性。

:path=/static-assets/word/content-code-examples/tutorials/rgba-color-value.cs
using IronWord;
using IronWord.Models;
using System;

// Open existing Word
WordDocument doc = new WordDocument("Accent1TextThemcolor.docx");

TextContent content = doc.Paragraphs[0].Texts[0];

// This will show the R G B A of the themecolor
var filledColor = content.Color;

// Print the filled color variable to the console
Console.WriteLine(filledColor);
Imports IronWord
Imports IronWord.Models
Imports System

' Open existing Word
Dim doc As New WordDocument("Accent1TextThemcolor.docx")

Dim content As TextContent = doc.Paragraphs(0).Texts(0)

' This will show the R G B A of the themecolor
Dim filledColor = content.Color

' Print the filled color variable to the console
Console.WriteLine(filledColor)
$vbLabelText   $csharpLabel

若要擷取顏色值,請使用 WordDocument 載入文件,接著存取 Paragraphs 集合與 Texts 陣列,以取得 TextContent 物件。 ColorTextContent 屬性會傳回文字現有顏色的 RGBA 值,讓您能在整個文件中維持一致的樣式。

嵌入圖片

此功能讓您能無縫地在內容中嵌入圖片,從而提升文件的整體視覺吸引力與溝通力。

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-embed-images.cs
using IronWord;
using IronWord.Models;

// Load docx
WordDocument doc = new WordDocument();

// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 200; // In unit pixel
image.Height = 200; // In unit pixel
TextContent textRun = new TextContent();

// Add image
Paragraph para = new Paragraph(textRun);
para.AddImage(image);

// Add paragraph
doc.AddParagraph(new Paragraph(textRun));

// Export docx
doc.SaveAs("save_document.docx");
Imports IronWord
Imports IronWord.Models

' Load docx
Private doc As New WordDocument()

' Configure image
Private image As New ImageContent("image.jpg")
image.Width = 200 ' In unit pixel
image.Height = 200 ' In unit pixel
Dim textRun As New TextContent()

' Add image
Dim para As New Paragraph(textRun)
para.AddImage(image)

' Add paragraph
doc.AddParagraph(New Paragraph(textRun))

' Export docx
doc.SaveAs("save_document.docx")
$vbLabelText   $csharpLabel

添加圖片

載入圖片

載入圖片是一個關鍵的過程。 這涉及將外部圖像檔案導入文件中。 支援載入圖片的功能有助於加入相關視覺素材,使文件更具吸引力且資訊更豐富。

:path=/static-assets/word/content-code-examples/tutorials/add-image-load-image.cs
using IronWord;
using IronWord.Models;

// Load docx
WordDocument doc = new WordDocument();

Paragraph paragraph = new Paragraph();

// Add image
paragraph.AddImage("image.jpg");

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models

' Load docx
Private doc As New WordDocument()

Private paragraph As New Paragraph()

' Add image
paragraph.AddImage("image.jpg")

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

設定圖片

透過可自訂的設定來優化圖片。 這包括設定文字換行、尺寸、位置以及距角落距離等屬性。 正確的設定可確保圖片以視覺上美觀且符合上下文的方式呈現。

:path=/static-assets/word/content-code-examples/tutorials/add-image-configure-image.cs
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
using IronSoftware.Abstractions.Word;

// Load docx
WordDocument doc = new WordDocument();

// Configure image
ImageContent image = new ImageContent("image.jpg");
image.TextWrapBehavior = new TextWrapSquare();
image.Width = 100;
image.Height = 100;
image.DistanceFromTop = 50;

var position = new ElementPosition();
position.X = 50;
position.Y = 50;
image.Position = position;

Paragraph paragraph = new Paragraph();

// Add image
paragraph.AddImage(image);

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
Imports IronSoftware.Abstractions.Word

' Load docx
Dim doc As New WordDocument()

' Configure image
Dim image As New ImageContent("image.jpg")
image.TextWrapBehavior = New TextWrapSquare()
image.Width = 100
image.Height = 100
image.DistanceFromTop = 50

Dim position As New ElementPosition()
position.X = 50
position.Y = 50
image.Position = position

Dim paragraph As New Paragraph()

' Add image
paragraph.AddImage(image)

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

常見問題

如何使用 C# 向 WORD 文件中添加文字?

您可以透過 IronWord 建立文字區塊的實例,並將其附加至文件中的段落,藉此在 WORD 文件中新增文字。

如何在 WORD 文件中分割文字?

IronWord 提供 Split 方法,可讓您根據指定的分隔符號將文字區塊分割成較小的段落,以便更輕鬆地進行文字處理。

如何使用 IronWord 在 WORD 文件中設定文字樣式?

您可以透過 IronWord 設定各種屬性(例如字型大小、顏色,以及粗體、斜體、刪除線、底線、上標和下標等樣式)來調整文字樣式。

如何使用 C# 在 WORD 文件中嵌入圖片?

若要使用 IronWord 在 WORD 文件中嵌入圖片,您可以從檔案載入圖片,並將其作為內嵌圖片新增至文件中的段落中。

將圖片載入 WORD 文件需要哪些步驟?

透過 IronWord,您可以從檔案或檔案串流載入圖片,藉此將視覺內容整合至 WORD 文件中。

如何在 WORD 文件中設定圖片屬性?

Using IronWord,您可以設定圖片屬性,例如文字環繞、尺寸、位置偏移以及距角落的距離,以確保圖片在文件中正確顯示。

我能否取得 WORD 文件中文字的 RGBA 顏色值?

是的,IronWord 允許您取得文件中現有文字的 RGBA 色彩值,以確保整體樣式的一致性。

如何開始使用 IronWord 進行 WORD 文件處理?

若要開始使用 IronWord,您可以將其整合至您的 .NET C# 應用程式中,藉助其全面的程式庫功能來建立、讀取及編輯 Word 文件。

Iron Software 針對 IronWord 提供哪些支援服務?

Iron Software 為 IronWord 提供全面支援,包括文件、教學指南及客戶支援,以協助開發者進行實作。

IronWord 是否有免費試用版?

是的,Iron Software 提供 IronWord 的免費試用版,讓開發人員能在決定購買前,先探索其功能與性能。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 44,829 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronWord
執行範例 觀看您的資料轉為 WORD 文件。