如何在 DOCX 中加入表格(C#) | IronWord

如何使用 C# 和 IronWord 將表格新增至 DOCX 檔案

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

IronWord 讓開發者能夠透過 C# 程式化地在 WORD 文件中新增表格,方法是建立具有指定列與行的 Table 物件,透過邊框與顏色進行樣式設定,並在儲存為 DOCX 檔案前將內容填入儲存格中。

快速入門:單次呼叫建立並儲存資料表

此範例示範如何在 IronWord 中建立表格。 建立具有特定尺寸的表格,套用樣式,加入內容,將其插入文件中,並儲存。 您可以在幾分鐘內生成一個包含格式化表格的 DOCX 檔案。

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

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

    var table = new IronWord.Models.Table(3,4);
    var doc = new IronWord.WordDocument();
    doc.AddTable(table);
    doc.SaveAs("QuickTable.docx");
  3. 部署至您的生產環境進行測試

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

    arrow pointer

如何在 WORD 文件中加入表格?

表格是 WORD 文件的基本組成部分。 首先,透過提供列數與行數來實例化 Table 類別。 設定表格的樣式,包括背景色、陰影、邊框、斑馬紋及寬度。 其次,使用直觀的 [row, column] 索引存取每個儲存格。 在每個儲存格中加入文字、圖片、圖形、段落,甚至表格。 最後,請將表格加入 WORD 文件中。

IronWord 中的表格為在 Word 文件中組織結構化資料提供了靈活的基礎。 無論是建立發票、報告或資料摘要,Table 類別皆能提供對內容與呈現形式的全面控制。 基於零的索引系統簡化了程式化的儲存格迭代,而豐富的樣式選項則確保了Professional的外觀。

提示所有列與行的索引位置均採用零起始索引。

:path=/static-assets/word/content-code-examples/how-to/add-table-add-table.cs
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;

WordDocument doc = new WordDocument();

// Create table
Table table = new Table(5, 3);

// Configure border style
BorderStyle borderStyle = new BorderStyle();
borderStyle.BorderColor = Color.Black;
borderStyle.BorderValue = BorderValues.Thick;
borderStyle.BorderSize = 5;

// Configure table border
TableBorders tableBorders = new TableBorders()
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle,
};

// Apply styling
table.Zebra = new ZebraColor("FFFFFF", "dddddd");
table.Borders = tableBorders;

// Populate table
table[0, 0] = new TableCell(new TextContent("Number"));
table[0, 1] = new TableCell(new TextContent("First Name"));
table[0, 2] = new TableCell(new TextContent("Last Name"));
for (int i = 1; i < table.Rows.Count; i++)
{
    table[i, 0].AddChild(new TextContent($"{i}"));
    table[i, 1].AddChild(new TextContent($"---"));
    table[i, 2].AddChild(new TextContent($"---"));
}

// Add table
doc.AddTable(table);

doc.Save("document.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums

Private doc As New WordDocument()

' Create table
Private table As New Table(5, 3)

' Configure border style
Private borderStyle As New BorderStyle()
borderStyle.BorderColor = Color.Black
borderStyle.BorderValue = BorderValues.Thick
borderStyle.BorderSize = 5

' Configure table border
Dim tableBorders As New TableBorders() With {
	.TopBorder = borderStyle,
	.RightBorder = borderStyle,
	.BottomBorder = borderStyle,
	.LeftBorder = borderStyle
}

' Apply styling
table.Zebra = New ZebraColor("FFFFFF", "dddddd")
table.Borders = tableBorders

' Populate table
table(0, 0) = New TableCell(New TextContent("Number"))
table(0, 1) = New TableCell(New TextContent("First Name"))
table(0, 2) = New TableCell(New TextContent("Last Name"))
For i As Integer = 1 To table.Rows.Count - 1
	table(i, 0).AddChild(New TextContent($"{i}"))
	table(i, 1).AddChild(New TextContent($"---"))
	table(i, 2).AddChild(New TextContent($"---"))
Next i

' Add table
doc.AddTable(table)

doc.Save("document.docx")
$vbLabelText   $csharpLabel
WORD 文件顯示一個空白的 4x3 表格,包含

AddChild 類別的 TableCell 方法接受一個 ContentElement 物件,其中包含段落、圖片、圖形和表格。 這使得在複雜的使用情境中能夠使用嵌套表格。

在處理表格儲存格時,IronWord 提供了多種內容管理方法。 您可以透過建構函式,使用初始內容建立 TableCell 的實例,或使用 AddChild 方法逐步新增內容。 這種靈活性允許建立結合不同內容類型的複雜儲存格結構。例如,單一儲存格可能包含一個標題段落,後接一張圖片,以及用於詳細規格的嵌套表格。

以下是一個展示進階儲存格填充技術的範例:

// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();

// Add a styled paragraph
Paragraph header = new Paragraph();
header.Add(new TextContent("Product Details").Bold().FontSize = 14);
complexCell.AddChild(header);

// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001").Bold());
complexCell.AddChild(new TextContent("\nPrice: $49.99"));

// Cells can also contain lists, images, and more
// This demonstrates the versatility of table cells in IronWord
// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();

// Add a styled paragraph
Paragraph header = new Paragraph();
header.Add(new TextContent("Product Details").Bold().FontSize = 14);
complexCell.AddChild(header);

// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001").Bold());
complexCell.AddChild(new TextContent("\nPrice: $49.99"));

// Cells can also contain lists, images, and more
// This demonstrates the versatility of table cells in IronWord
' Example: Creating cells with mixed content
Dim complexCell As New TableCell()

' Add a styled paragraph
Dim header As New Paragraph()
header.Add(New TextContent("Product Details").Bold().FontSize = 14)
complexCell.AddChild(header)

' Add multiple text elements
complexCell.AddChild(New TextContent("SKU: "))
complexCell.AddChild(New TextContent("PROD-001").Bold())
complexCell.AddChild(New TextContent(vbCrLf & "Price: $49.99"))

' Cells can also contain lists, images, and more
' This demonstrates the versatility of table cells in IronWord
$vbLabelText   $csharpLabel

我可以對表格套用哪些樣式選項?

IronWord 提供豐富的表格樣式設定功能,可協助建立視覺上美觀且 Professional 的文件。 除了基本的邊框與顏色設定外,還需控制儲存格的內距、對齊方式,並透過斑馬條紋效果套用條件格式。 此樣式系統結合了強大功能與直覺化設計,採用熟悉的屬性名稱及清晰的數值枚舉。

有哪些邊框樣式可供選擇?

使用 BorderValues 枚舉探索所有可用的邊界值選項:

WORD 邊框樣式選單,顯示

BorderValues 枚舉提供了全面的表格美學選項。 從簡單的單一線條到波浪、圓點等複雜圖案,每種風格皆服務於特定的設計目的。 商務文件適合採用Professional雙線或三線邊框,而創意文件則適合使用波浪線或點線圖案。 BorderSize 屬性與 BorderValue 配合使用,可精確控制線條粗細,單位以八分之一點為準。

以下是一個展示不同邊框設定的實用範例:

// Example: Applying different borders to table sections
Table styledTable = new Table(4, 4);

// Create distinct border styles for header and body
BorderStyle headerBorder = new BorderStyle
{
    BorderColor = Color.Navy,
    BorderValue = BorderValues.Double,
    BorderSize = 8
};

BorderStyle bodyBorder = new BorderStyle
{
    BorderColor = Color.Gray,
    BorderValue = BorderValues.Dotted,
    BorderSize = 3
};

// Apply different borders to different parts of the table
// This creates visual hierarchy and improves readability
styledTable.Borders = new TableBorders
{
    TopBorder = headerBorder,
    BottomBorder = headerBorder,
    LeftBorder = bodyBorder,
    RightBorder = bodyBorder,
    InsideHorizontalBorder = bodyBorder,
    InsideVerticalBorder = bodyBorder
};

// Zebra striping for better row distinction
styledTable.Zebra = new ZebraColor("F5F5F5", "FFFFFF");
// Example: Applying different borders to table sections
Table styledTable = new Table(4, 4);

// Create distinct border styles for header and body
BorderStyle headerBorder = new BorderStyle
{
    BorderColor = Color.Navy,
    BorderValue = BorderValues.Double,
    BorderSize = 8
};

BorderStyle bodyBorder = new BorderStyle
{
    BorderColor = Color.Gray,
    BorderValue = BorderValues.Dotted,
    BorderSize = 3
};

// Apply different borders to different parts of the table
// This creates visual hierarchy and improves readability
styledTable.Borders = new TableBorders
{
    TopBorder = headerBorder,
    BottomBorder = headerBorder,
    LeftBorder = bodyBorder,
    RightBorder = bodyBorder,
    InsideHorizontalBorder = bodyBorder,
    InsideVerticalBorder = bodyBorder
};

// Zebra striping for better row distinction
styledTable.Zebra = new ZebraColor("F5F5F5", "FFFFFF");
Imports System.Drawing

' Example: Applying different borders to table sections
Dim styledTable As New Table(4, 4)

' Create distinct border styles for header and body
Dim headerBorder As New BorderStyle With {
    .BorderColor = Color.Navy,
    .BorderValue = BorderValues.Double,
    .BorderSize = 8
}

Dim bodyBorder As New BorderStyle With {
    .BorderColor = Color.Gray,
    .BorderValue = BorderValues.Dotted,
    .BorderSize = 3
}

' Apply different borders to different parts of the table
' This creates visual hierarchy and improves readability
styledTable.Borders = New TableBorders With {
    .TopBorder = headerBorder,
    .BottomBorder = headerBorder,
    .LeftBorder = bodyBorder,
    .RightBorder = bodyBorder,
    .InsideHorizontalBorder = bodyBorder,
    .InsideVerticalBorder = bodyBorder
}

' Zebra striping for better row distinction
styledTable.Zebra = New ZebraColor("F5F5F5", "FFFFFF")
$vbLabelText   $csharpLabel

表格的寬度與對齊屬性可提供額外的版面配置控制。 將表格設定為特定寬度或百分比,在文件中對齊表格,並控制其與周圍內容的互動。 儲存格層級的樣式設定選項包含個別背景顏色、文字對齊方式及內距調整,可對表格外觀的每個細節進行精細控制。

這些樣式選項可協助建立符合任何文件設計需求的表格,從簡單的数据網格到具有多重視覺層級的複雜財務報表皆可涵蓋。

常見問題

如何在 WORD 文件中建立具有特定尺寸的表格?

透過 IronWord,您可以透過實例化 Table 類別並指定列與行的數量來建立表格。例如,使用 'var table = new IronWord.Models.Table(3,4);' 可建立一個 3 行 4 列的表格。接著將其新增至 WordDocument 物件,並儲存為 DOCX 檔案。

我可以透過程式設計為表格設定邊框和顏色嗎?

是的,IronWord 允許您設定全面的表格樣式,包括背景顏色、陰影、邊框、交錯條紋及寬度。您可以在將表格物件加入 WORD 文件之前,先將這些樣式套用至該物件。

如何存取並填入表格中的特定儲存格?

IronWord 採用從零開始的索引方式來存取表格儲存格。您可以使用直觀的 [行, 列] 表示法存取儲存格,然後將各種內容類型填入其中,包括文字、圖片、圖形、段落,甚至嵌套表格。

我可以在表格儲存格中加入哪些類型的內容?

Using IronWord's TableCell class, you can use the AddChild method, which accepts ContentElement objects, to add multiple content types. This includes paragraphs, images, shapes, and even tables for creating nested table structures.

是否可以在表格儲存格內建立嵌套表格?

是的,IronWord 支援嵌套表格。由於 AddChild 方法接受包含表格的 ContentElement 物件,您可以在表格儲存格內新增表格,以處理複雜的資料組織需求。

要建立包含表格的 DOCX 檔案,最快速的方法是什麼?

using IronWord 最快速的方法是建立一個具有尺寸的 Table 物件,實例化一個 WordDocument,透過 AddTable() 加入表格,並使用 SaveAs() 儲存。整個過程僅需 4 行程式碼即可完成。

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 文件。