如何使用 C# 添加 Excel 命名表 | IronXL

如何在 Excel 中使用 C# 添加命名表

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

要在 Excel 中使用 C# 添加命名表,请使用 IronXL.Excel 的 AddNamedTable 方法,并为表名、范围和可选样式设置参数--只需调用一次方法即可实现结构化数据管理。

命名表也常被称为 Excel 表,它指的是一种特定类型的区域,该区域已指定名称,并具有与之关联的附加功能和属性。 命名表格提供了增强的数据组织能力、自动格式化、内置筛选功能以及与 Excel 公式的无缝集成,因此对于在Excel 自动化工作流中管理结构化数据集来说至关重要。

快速入门:在一行中创建表格并为其命名。

本示例展示了如何使用 IronXL 在工作表中添加命名表——只需一次清晰的方法调用即可定义名称、范围、筛选可见性和样式。

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronXL

    PM > Install-Package IronXL.Excel

  2. 复制并运行这段代码。

    var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXL.Styles.TableStyles.Medium2);
  3. 部署到您的生产环境中进行测试

    立即开始在您的项目中使用 IronXL,免费试用!
    arrow pointer


如何在 Excel 工作表中添加命名表?

要添加命名表,请使用AddNamedTable方法。 该方法需要以字符串形式提供表名,以及范围对象。 您还可以选择指定表格样式以及是否显示过滤器。 该功能在处理 DataSetDataTable 导入(其中结构化数据需要适当组织)时尤其有用。

// Example code to add a named table using IronXL
using IronXL;
using IronXL.Styles;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Define the range for the named table
var range = workSheet["A1:B10"];

// Add a named table with the specified name and range
var namedTable = workSheet.AddNamedTable("MyTable", range);

// Optionally, set table style and visibility of the filter
namedTable.SetStyle(TableStyles.Dark10);
namedTable.ShowFilter = true;

// Save the modified workbook
workbook.SaveAs("modified_example.xlsx");
// Example code to add a named table using IronXL
using IronXL;
using IronXL.Styles;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Define the range for the named table
var range = workSheet["A1:B10"];

// Add a named table with the specified name and range
var namedTable = workSheet.AddNamedTable("MyTable", range);

// Optionally, set table style and visibility of the filter
namedTable.SetStyle(TableStyles.Dark10);
namedTable.ShowFilter = true;

// Save the modified workbook
workbook.SaveAs("modified_example.xlsx");
' Example code to add a named table using IronXL
Imports IronXL
Imports IronXL.Styles

' Load the Excel workbook
Private workbook = WorkBook.Load("example.xlsx")
' Select the worksheet
Private workSheet = workbook.WorkSheets.First()

' Define the range for the named table
Private range = workSheet("A1:B10")

' Add a named table with the specified name and range
Private namedTable = workSheet.AddNamedTable("MyTable", range)

' Optionally, set table style and visibility of the filter
namedTable.SetStyle(TableStyles.Dark10)
namedTable.ShowFilter = True

' Save the modified workbook
workbook.SaveAs("modified_example.xlsx")
$vbLabelText   $csharpLabel

命名表格通过 TableStyles 枚举支持各种样式选项。 您可以即时应用专业格式,这是对 单元格样式和边框等其他格式功能的补充。 下面是一个演示不同表格风格应用的示例:

// Example: Creating multiple styled named tables
using IronXL;
using IronXL.Styles;

var workbook = WorkBook.Create();
var sheet = workbook.CreateWorkSheet("SalesData");

// Add sample data
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Sales";
sheet["C1"].Value = "Revenue";

// Populate data rows
for (int i = 2; i <= 10; i++)
{
    sheet[$"A{i}"].Value = $"Product {i-1}";
    sheet[$"B{i}"].IntValue = i * 100;
    sheet[$"C{i}"].DecimalValue = i * 250.50m;
}

// Create a light-styled table
var salesTable = sheet.AddNamedTable("SalesTable", sheet["A1:C10"], 
    showFilter: true, 
    tableStyle: TableStyles.Light15);

// Create another table with dark styling
sheet["E1"].Value = "Region";
sheet["F1"].Value = "Performance";
var regionTable = sheet.AddNamedTable("RegionData", sheet["E1:F5"], 
    showFilter: false, 
    tableStyle: TableStyles.Dark3);

workbook.SaveAs("styled_tables.xlsx");
// Example: Creating multiple styled named tables
using IronXL;
using IronXL.Styles;

var workbook = WorkBook.Create();
var sheet = workbook.CreateWorkSheet("SalesData");

// Add sample data
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Sales";
sheet["C1"].Value = "Revenue";

// Populate data rows
for (int i = 2; i <= 10; i++)
{
    sheet[$"A{i}"].Value = $"Product {i-1}";
    sheet[$"B{i}"].IntValue = i * 100;
    sheet[$"C{i}"].DecimalValue = i * 250.50m;
}

// Create a light-styled table
var salesTable = sheet.AddNamedTable("SalesTable", sheet["A1:C10"], 
    showFilter: true, 
    tableStyle: TableStyles.Light15);

// Create another table with dark styling
sheet["E1"].Value = "Region";
sheet["F1"].Value = "Performance";
var regionTable = sheet.AddNamedTable("RegionData", sheet["E1:F5"], 
    showFilter: false, 
    tableStyle: TableStyles.Dark3);

workbook.SaveAs("styled_tables.xlsx");
Imports IronXL
Imports IronXL.Styles

Dim workbook = WorkBook.Create()
Dim sheet = workbook.CreateWorkSheet("SalesData")

' Add sample data
sheet("A1").Value = "Product"
sheet("B1").Value = "Sales"
sheet("C1").Value = "Revenue"

' Populate data rows
For i As Integer = 2 To 10
    sheet($"A{i}").Value = $"Product {i - 1}"
    sheet($"B{i}").IntValue = i * 100
    sheet($"C{i}").DecimalValue = i * 250.5D
Next

' Create a light-styled table
Dim salesTable = sheet.AddNamedTable("SalesTable", sheet("A1:C10"), 
    showFilter:=True, 
    tableStyle:=TableStyles.Light15)

' Create another table with dark styling
sheet("E1").Value = "Region"
sheet("F1").Value = "Performance"
Dim regionTable = sheet.AddNamedTable("RegionData", sheet("E1:F5"), 
    showFilter:=False, 
    tableStyle:=TableStyles.Dark3)

workbook.SaveAs("styled_tables.xlsx")
$vbLabelText   $csharpLabel
Excel 电子表格,显示包含三列和格式化标题的命名表格,其中包含示例文本数据

如何从工作表中检索命名表?

什么方法可以返回工作表中所有已命名的表?

GetNamedTableNames 方法以字符串列表的形式返回工作表中所有已命名表格。 这在处理包含多个表格的工作簿或使用动态数据结构管理工作表时尤其有用。

// Example code to retrieve all named table names using IronXL
using IronXL;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Retrieve all named table names
var tableNames = workSheet.GetNamedTableNames();

// Output each table name
foreach (var name in tableNames)
{
    Console.WriteLine("Named Table: " + name);
}
// Example code to retrieve all named table names using IronXL
using IronXL;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Retrieve all named table names
var tableNames = workSheet.GetNamedTableNames();

// Output each table name
foreach (var name in tableNames)
{
    Console.WriteLine("Named Table: " + name);
}
' Example code to retrieve all named table names using IronXL
Imports IronXL

' Load the Excel workbook
Private workbook = WorkBook.Load("example.xlsx")
' Select the worksheet
Private workSheet = workbook.WorkSheets.First()

' Retrieve all named table names
Private tableNames = workSheet.GetNamedTableNames()

' Output each table name
For Each name In tableNames
	Console.WriteLine("Named Table: " & name)
Next name
$vbLabelText   $csharpLabel

如何通过表名访问特定的命名表?

使用GetNamedTable方法检索工作表中指定的表名。 检索后,您可以访问各种属性并执行单元格范围排序或应用条件格式化等操作。

// Example code to retrieve a specific named table using IronXL
using IronXL;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Retrieve a specific named table
var namedTable = workSheet.GetNamedTable("MyTable");

// Output some information about the table
Console.WriteLine("Named Table: " + namedTable.Name);
Console.WriteLine("Rows: " + namedTable.Rows);
// Example code to retrieve a specific named table using IronXL
using IronXL;

// Load the Excel workbook
var workbook = WorkBook.Load("example.xlsx");
// Select the worksheet
var workSheet = workbook.WorkSheets.First();

// Retrieve a specific named table
var namedTable = workSheet.GetNamedTable("MyTable");

// Output some information about the table
Console.WriteLine("Named Table: " + namedTable.Name);
Console.WriteLine("Rows: " + namedTable.Rows);
' Example code to retrieve a specific named table using IronXL
Imports IronXL

' Load the Excel workbook
Private workbook = WorkBook.Load("example.xlsx")
' Select the worksheet
Private workSheet = workbook.WorkSheets.First()

' Retrieve a specific named table
Private namedTable = workSheet.GetNamedTable("MyTable")

' Output some information about the table
Console.WriteLine("Named Table: " & namedTable.Name)
Console.WriteLine("Rows: " & namedTable.Rows)
$vbLabelText   $csharpLabel

使用表格数据

命名表提供了强大的数据操作能力。 下面是一个综合示例,展示了如何使用表格数据:

// Advanced named table operations
using IronXL;
using System.Linq;

var workbook = WorkBook.Load("sales_data.xlsx");
var sheet = workbook.DefaultWorkSheet;

// Create a named table from existing data
var dataRange = sheet["A1:D20"];
var salesTable = sheet.AddNamedTable("MonthlySales", dataRange, true);

// Access table data for calculations
var tableRange = salesTable.TableRange;

// Sum values in a specific column (assuming column C contains numeric data)
decimal totalSales = 0;
for (int row = 2; row <= tableRange.RowCount; row++)
{
    var cellValue = sheet[$"C{row}"].DecimalValue;
    totalSales += cellValue;
}

// Add summary row
var summaryRow = tableRange.RowCount + 1;
sheet[$"B{summaryRow}"].Value = "Total:";
sheet[$"C{summaryRow}"].Value = totalSales;

// Apply formatting to the summary row
sheet[$"B{summaryRow}:D{summaryRow}"].Style.Font.Bold = true;
sheet[$"B{summaryRow}:D{summaryRow}"].Style.SetBackgroundColor("#FFE599");

workbook.SaveAs("sales_with_summary.xlsx");
// Advanced named table operations
using IronXL;
using System.Linq;

var workbook = WorkBook.Load("sales_data.xlsx");
var sheet = workbook.DefaultWorkSheet;

// Create a named table from existing data
var dataRange = sheet["A1:D20"];
var salesTable = sheet.AddNamedTable("MonthlySales", dataRange, true);

// Access table data for calculations
var tableRange = salesTable.TableRange;

// Sum values in a specific column (assuming column C contains numeric data)
decimal totalSales = 0;
for (int row = 2; row <= tableRange.RowCount; row++)
{
    var cellValue = sheet[$"C{row}"].DecimalValue;
    totalSales += cellValue;
}

// Add summary row
var summaryRow = tableRange.RowCount + 1;
sheet[$"B{summaryRow}"].Value = "Total:";
sheet[$"C{summaryRow}"].Value = totalSales;

// Apply formatting to the summary row
sheet[$"B{summaryRow}:D{summaryRow}"].Style.Font.Bold = true;
sheet[$"B{summaryRow}:D{summaryRow}"].Style.SetBackgroundColor("#FFE599");

workbook.SaveAs("sales_with_summary.xlsx");
Imports IronXL
Imports System.Linq

Dim workbook = WorkBook.Load("sales_data.xlsx")
Dim sheet = workbook.DefaultWorkSheet

' Create a named table from existing data
Dim dataRange = sheet("A1:D20")
Dim salesTable = sheet.AddNamedTable("MonthlySales", dataRange, True)

' Access table data for calculations
Dim tableRange = salesTable.TableRange

' Sum values in a specific column (assuming column C contains numeric data)
Dim totalSales As Decimal = 0
For row As Integer = 2 To tableRange.RowCount
    Dim cellValue = sheet($"C{row}").DecimalValue
    totalSales += cellValue
Next

' Add summary row
Dim summaryRow = tableRange.RowCount + 1
sheet($"B{summaryRow}").Value = "Total:"
sheet($"C{summaryRow}").Value = totalSales

' Apply formatting to the summary row
sheet($"B{summaryRow}:D{summaryRow}").Style.Font.Bold = True
sheet($"B{summaryRow}:D{summaryRow}").Style.SetBackgroundColor("#FFE599")

workbook.SaveAs("sales_with_summary.xlsx")
$vbLabelText   $csharpLabel

与 IronXL 其他功能的集成

命名表格可与 IronXL 的其他功能无缝配合。 您可以将它们与公式结合起来进行动态计算,或者在创建图表时将它们用作数据源。 在导出到不同格式之前,它们也是整理数据的绝佳工具。

// Example: Named table with formulas
using IronXL;

var workbook = WorkBook.Create();
var sheet = workbook.CreateWorkSheet("Analysis");

// Create data structure
sheet["A1"].Value = "Item";
sheet["B1"].Value = "Quantity";
sheet["C1"].Value = "Price";
sheet["D1"].Value = "Total";

// Add sample data
for (int i = 2; i <= 6; i++)
{
    sheet[$"A{i}"].Value = $"Item {i-1}";
    sheet[$"B{i}"].IntValue = i * 10;
    sheet[$"C{i}"].DecimalValue = i * 15.99m;
    // Add formula to calculate total
    sheet[$"D{i}"].Formula = $"=B{i}*C{i}";
}

// Create named table including the formula column
var priceTable = sheet.AddNamedTable("PriceCalculations", sheet["A1:D6"], 
    showFilter: true, 
    tableStyle: TableStyles.Medium9);

// Add a grand total formula
sheet["C7"].Value = "Grand Total:";
sheet["D7"].Formula = "=SUM(D2:D6)";
sheet["D7"].Style.Font.Bold = true;

workbook.SaveAs("table_with_formulas.xlsx");
// Example: Named table with formulas
using IronXL;

var workbook = WorkBook.Create();
var sheet = workbook.CreateWorkSheet("Analysis");

// Create data structure
sheet["A1"].Value = "Item";
sheet["B1"].Value = "Quantity";
sheet["C1"].Value = "Price";
sheet["D1"].Value = "Total";

// Add sample data
for (int i = 2; i <= 6; i++)
{
    sheet[$"A{i}"].Value = $"Item {i-1}";
    sheet[$"B{i}"].IntValue = i * 10;
    sheet[$"C{i}"].DecimalValue = i * 15.99m;
    // Add formula to calculate total
    sheet[$"D{i}"].Formula = $"=B{i}*C{i}";
}

// Create named table including the formula column
var priceTable = sheet.AddNamedTable("PriceCalculations", sheet["A1:D6"], 
    showFilter: true, 
    tableStyle: TableStyles.Medium9);

// Add a grand total formula
sheet["C7"].Value = "Grand Total:";
sheet["D7"].Formula = "=SUM(D2:D6)";
sheet["D7"].Style.Font.Bold = true;

workbook.SaveAs("table_with_formulas.xlsx");
Imports IronXL

Dim workbook = WorkBook.Create()
Dim sheet = workbook.CreateWorkSheet("Analysis")

' Create data structure
sheet("A1").Value = "Item"
sheet("B1").Value = "Quantity"
sheet("C1").Value = "Price"
sheet("D1").Value = "Total"

' Add sample data
For i As Integer = 2 To 6
    sheet($"A{i}").Value = $"Item {i - 1}"
    sheet($"B{i}").IntValue = i * 10
    sheet($"C{i}").DecimalValue = i * 15.99D
    ' Add formula to calculate total
    sheet($"D{i}").Formula = $"=B{i}*C{i}"
Next

' Create named table including the formula column
Dim priceTable = sheet.AddNamedTable("PriceCalculations", sheet("A1:D6"), 
    showFilter:=True, 
    tableStyle:=TableStyles.Medium9)

' Add a grand total formula
sheet("C7").Value = "Grand Total:"
sheet("D7").Formula = "=SUM(D2:D6)"
sheet("D7").Style.Font.Bold = True

workbook.SaveAs("table_with_formulas.xlsx")
$vbLabelText   $csharpLabel

IronXL还可以添加命名范围。 了解更多信息,请参阅"如何添加命名范围"

常见问题解答

什么是 Excel 中的命名表?

Excel 中的命名表是一种特定类型的范围,已指定名称并包含附加功能。IronXL 可让您用 C# 以编程方式创建这些表格,提供增强的数据组织功能、自动格式化、内置过滤以及与 Excel 公式的无缝集成。

如何使用 C# 在 Excel 工作表中添加命名表?

要使用 IronXL 添加命名表,请使用 AddNamedTable 方法。该方法需要以字符串形式提供表名和范围对象。可以选择指定表格样式和筛选器可见性。例如:workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle:IronXL.Styles.TableStyles.Medium2)。

能否对已命名的表格应用自定义样式?

是的,IronXL 通过 TableStyles 枚举支持命名表格的各种样式选项。您可以使用 Dark10、Medium2 等样式和其他预定义的表格样式即时应用专业格式。只需在创建表格时使用 SetStyle 方法或指定 tableStyle 参数即可。

是否可以在已命名表格中显示或隐藏过滤器?

当然可以!IronXL 允许您控制命名表中过滤器的可见性。您可以将 ShowFilter 属性设置为 true 或 false,也可以在创建表格时使用 AddNamedTable 方法中的 showFilter 参数直接指定该属性。

创建命名表需要哪些参数?

IronXL 中的 AddNamedTable 方法需要两个基本参数:表名(字符串)和定义表区域的范围对象。可选参数包括 showFilter(布尔值)和 tableStyle(来自 TableStyles 枚举)。

能否在同一工作表中创建多个样式命名表?

是的,IronXL 允许您在同一工作表中创建多个具有不同风格的命名表格。每个表格都可以有自己独特的名称、范围、样式和过滤器设置,因此非常适合在单个 Excel 文件中组织不同的数据集。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 1,846,091 | 版本: 2026.2 刚刚发布