How to Add Table to DOCX C#

如何使用IronWord在C#中將表格新增到DOCX中

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

IronWord使開發人員能夠透過C#程式設計方式,藉由建立具有指定列和行的Table物件,為Word文件新增表格,並透過邊框和顏色進行樣式設定,在儲存為DOCX文件之前填充儲存格內容。

快速開始:一鍵建立並儲存表格

此範例演示如何在IronWord中建立表格。 構建具有規格的表格,應用樣式,新增內容,插入文件並儲存。 您可以在幾分鐘內生成帶有樣式表格的DOCX文件。

  1. 使用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類都提供了對內容和展現的全面控制。 基於零的索引系統簡化了程式化的儲存格迭代,而豐富的樣式選項確保專業的外觀。

提示所有行和列的索引位置都遵循零基索引。

: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.Style.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

Dim doc As New WordDocument()

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

' Configure border style
Dim 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.Style.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

' Add table
doc.AddTable(table)

doc.Save("document.docx")
$vbLabelText   $csharpLabel
Word文件顯示空的4x3表格,具有編號、名字、姓氏列和交替行陰影

ContentElement物件,其中包含段落、圖片、形狀和表格。 這使得複雜使用案例中巢狀表格成為可能。

在處理表格儲存格時,IronWord 提供多種內容管理方法。 使用構造函式初始化具有初始內容的AddChild方法逐步新增內容。 此靈活性允許構建結合不同內容型別的複雜儲存格結構。例如,單個儲存格可能包含一個標題段落,接著是一個圖片和一個巢狀表格以進行詳細說明。

這裡有一個範例展示高級儲存格填充技術:

:path=/static-assets/word/content-code-examples/how-to/add-table-3.cs
// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();

// Add a styled paragraph
Paragraph header = new Paragraph();
TextContent headerText = new TextContent("Product Details") { IsBold = true, FontSize = 14 };
header.AddText(headerText);
complexCell.AddChild(header);

// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001") { IsBold = true });
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()
Dim headerText As New TextContent("Product Details") With {.IsBold = True, .FontSize = 14}
header.AddText(headerText)
complexCell.AddChild(header)

' Add multiple text elements
complexCell.AddChild(New TextContent("SKU: "))
complexCell.AddChild(New TextContent("PROD-001") With {.IsBold = True})
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枚舉提供了桌子美學的完整選項。 從簡單的單線到波形和點狀等複雜圖案,每種樣式都服務於特定的設計目的。 商務文件受益於專業的雙線或三線邊框,而創意文件則利用波形或DashDot圖案。 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行x4列的表格。然後將其新增到WordDocument物件中並保存為DOCX文件。

我可以程式化地設計具邊框和顏色的表格嗎?

是的,IronWord允許您配置全面的表格樣式,包括背景色、陰影、邊框、斑馬條紋和寬度。在將表格物件新增到Word文件之前,您可以將這些樣式應用於它。

如何存取和填充表格中的特定單元格?

IronWord使用從零開始的索引來存取表格單元格。您可以使用直觀的[行,列]表示法存取單元格,然後用包括文字、圖片、形狀、段落甚至巢狀表格等各種內容型別填充它們。

我可以在表格單元格中新增哪些型別的內容?

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

能否在表格單元格內建立巢狀表格?

可以,IronWord支持巢狀表格。由於AddChild方法接受包括表格在內的ContentElement物件,因此您可以在表格單元格內新增表格來處理複雜資料組織需求。

生成帶有表格的DOCX文件的最快方法是什麼?

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

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檔。