如何在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. 使用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:文件中的內容塊
  • TextContent的包裝物件,可以應用樣式
  • TextContent:實際的文字字串

向段落中新增內容

IronWord提供了兩種方法來向段落中新增內容:

  • AddText(TextContent):用於無樣式純文字。 直接將TextContent新增到段落中。
  • AddChild(Run):用於樣式化文字。 將包含Run物件新增到段落中。

當您需要應用樣式如字體大小、顏色或粗體格式時,建立一個AddChild將其新增到段落中。

新增TextRuns

文字內容

使用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包裝模式。 建立一個包含TextContent)。 FontSize、顏色、粗體、斜體、刪除線、下劃線、上標和下標。

請注意,TextFont屬性中設置。 一旦設置了樣式,使用Run新增到段落中。 這遵循文件層次結構: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.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.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

要檢索顏色值,請使用TextContent物件。 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(para);

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

' Load docx
Dim doc As New WordDocument()

' Configure image
Dim 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(para)

' 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;

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

// Configure image
ImageContent image = new ImageContent("image.jpg");
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

' Load docx
Dim doc As New WordDocument()

' Configure image
Dim image As New ImageContent("image.jpg")
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文件中配置圖片屬性?

使用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大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 49,323 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

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