如何向 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 檔案。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 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 類別都能提供對內容和呈現的全面控制。 零基索引系統簡化了程式單元格的迭代,而豐富的樣式選項確保了專業的外觀。

所有行和列索引位置均採用從零開始的索引方式。

: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表格,其中包含號碼、名稱、姓氏列以及交替的行陰影

TableCell 類的 AddChild 方法接受 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 提供廣泛的表格樣式設計功能,可建立視覺上吸引人且專業的文件。 除了基本的邊框和顏色之外,還可以控制儲存格的襯墊、對齊方式,並透過斑馬線套用條件格式。 造型系統結合了強大的功能與直覺的設計,使用熟悉的屬性名稱和清楚的數值枚舉。

哪些邊框樣式可用?

使用 BorderValues 枚舉探討邊緣值的所有可用選項:

Word邊框樣式選單,顯示單色、雙色、三色、圓點、虛線、波浪等選項,以及各種厚度組合

BorderValues 枚舉為表格美學提供了全面的選項。 從簡單的單線到複雜的圖案(如波浪和點),每種樣式都能達到特定的設計目的。 商業文件受益於專業的 Double 或 Triple 邊框,而創意文件則利用 Wave 或 DashDot 模式。 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 使用基於零的索引來存取表格儲存格。您可以使用直觀的 [row, column] 符號存取儲存格,然後以各種內容類型填充儲存格,包括文字、圖片、圖形、段落,甚至嵌套表格。

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

使用 IronWord 的 TableCell 類別,您可以透過 AddChild 方法新增多種內容類型,該方法接受 ContentElement 物件。這包括段落、圖片、圖形,甚至是用來建立巢狀表格結構的表格。

是否可以在表格單元格中建立嵌套表格?

是的,IronWord 支援嵌套表格。由於 AddChild 方法接受包括表格在內的 ContentElement 物件,因此您可以在表格單元格內加入表格,以處理複雜的資料組織需求。

有什麼方法可以快速生成帶表格的 DOCX 檔案?

使用 IronWord 的最快方法是建立具有尺寸的 Table 物件,實體化 WordDocument,使用 AddTable() 新增表格,並使用 SaveAs() 儲存。整個過程只需 4 行代碼即可完成。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 32,629 | 版本: 2026.2 剛剛發布