Cómo agregar una tabla nombrada en Excel utilizando C# | IronXL

Cómo añadir una tabla con nombre en Excel usando C#

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

Para agregar una tabla con nombre en Excel usando C#, utilice el método AddNamedTable de IronXL con parámetros para el nombre de la tabla, el rango y el estilo opcional, lo que permite la gestión de datos estructurados con una sola llamada al método.

Una tabla nombrada también se conoce comúnmente como una tabla de Excel, que se refiere a un tipo específico de rango que ha sido designado con un nombre y tiene funcionalidad y propiedades adicionales asociadas a él. Las tablas con nombre proporcionan capacidades mejoradas de organización de datos, formato automático, filtrado incorporado e integración perfecta con fórmulas de Excel, lo que las hace esenciales para gestionar conjuntos de datos estructurados en flujos de trabajo de automatización de Excel.

Inicio rápido: Crear y nombrar una tabla en una línea

Este ejemplo muestra cuán fácilmente puedes agregar una tabla nombrada en tu hoja de trabajo usando IronXL—define el nombre, rango, visibilidad del filtro y estilo, todo en una sola llamada de método clara.

Nuget IconEmpieza a crear PDF con NuGet ahora:

  1. Instalar IronXL con el gestor de paquetes NuGet

    PM > Install-Package IronXL.Excel

  2. Copie y ejecute este fragmento de código.

    var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXL.Styles.TableStyles.Medium2);
  3. Despliegue para probar en su entorno real

    Empieza a utilizar IronXL en tu proyecto hoy mismo con una prueba gratuita
    arrow pointer


¿Cómo añado una tabla con nombre a mi hoja de cálculo de Excel?

Para agregar una tabla nombrada, utiliza el método AddNamedTable. El método requiere el nombre de la tabla como cadena de texto y el objeto de rango. También tiene la opción de especificar el estilo de la tabla y si desea mostrar el filtro. Esta funcionalidad es particularmente útil cuando se trabaja con <código>DataSet</código> y <código>DataTable</código> importaciones donde los datos estructurados necesitan una organización adecuada.

// 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");
$vbLabelText   $csharpLabel

Las tablas con nombre admiten varias opciones de estilo mediante la enumeración TableStyles. Puede aplicar un formato profesional al instante, lo que complementa otras funciones de formato como el estilo y los bordes de las celdas. He aquí un ejemplo que muestra diferentes aplicaciones de estilo tabla:

// 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");
$vbLabelText   $csharpLabel
Hoja de cálculo de Excel que muestra una tabla con nombre con tres columnas y encabezados formateados que contienen datos de texto de muestra

¿Cómo puedo recuperar tablas con nombre de mi hoja de cálculo?

¿Qué método devuelve todas las tablas con nombre de una hoja de cálculo?

El método GetNamedTableNames devuelve todas las tablas con nombre de la hoja de cálculo como una lista de cadenas. Esto resulta especialmente útil cuando se trabaja con libros de trabajo que contienen varias tablas o cuando se gestionan hojas de trabajo con estructuras de datos dinámicas.

// 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);
}
$vbLabelText   $csharpLabel

¿Cómo accedo a una tabla específica por su nombre?

Utiliza el método GetNamedTable para recuperar una tabla nombrada específica en la hoja de trabajo. Una vez recuperadas, se puede acceder a varias propiedades y realizar operaciones como clasificar rangos de celdas o aplicar formateo condicional.

// 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);
$vbLabelText   $csharpLabel

Trabajar con datos de tabla

Las tablas con nombre ofrecen potentes funciones de manipulación de datos. He aquí un ejemplo exhaustivo que muestra cómo trabajar con datos de tablas:

// 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");
$vbLabelText   $csharpLabel

Integración con otras funciones de IronXL

Las tablas con nombre funcionan a la perfección con otras funciones de IronXL. Puede combinarlas con fórmulas para realizar cálculos dinámicos o utilizarlas como fuentes de datos al crear gráficos. También son excelentes para organizar datos antes de exportarlos a diferentes formatos.

// 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");
$vbLabelText   $csharpLabel

IronXL también puede agregar rangos nombrados. Aprende más en Cómo agregar un rango nombrado.

Preguntas Frecuentes

¿Qué es una tabla con nombre en Excel?

Una tabla con nombre en Excel es un tipo específico de rango que ha sido designado con un nombre e incluye funcionalidad adicional. IronXL le permite crear estas tablas mediante programación en C#, proporcionando capacidades mejoradas de organización de datos, formato automático, filtrado incorporado e integración perfecta con fórmulas de Excel.

¿Cómo añado una tabla con nombre a una hoja de cálculo de Excel utilizando C#?

Para agregar una tabla con nombre utilizando IronXL, utilice el método AddNamedTable. Este método requiere el nombre de la tabla como una cadena y un objeto de rango. Puede especificar opcionalmente el estilo de la tabla y la visibilidad del filtro. Por ejemplo: workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXL.Styles.TableStyles.Medium2).

¿Puedo aplicar estilos personalizados a las tablas con nombre?

Sí, IronXL admite varias opciones de estilo para tablas con nombre a través de la enumeración TableStyles. Puede aplicar un formato profesional al instante utilizando estilos como Dark10, Medium2 y otros estilos de tabla predefinidos. Simplemente utilice el método SetStyle o especifique el parámetro tableStyle al crear la tabla.

¿Es posible mostrar u ocultar filtros en tablas con nombre?

Por supuesto IronXL le permite controlar la visibilidad de los filtros en las tablas con nombre. Puede establecer la propiedad ShowFilter en true o false, o especificarla directamente al crear la tabla utilizando el parámetro showFilter en el método AddNamedTable.

¿Cuáles son los parámetros necesarios para crear una tabla con nombre?

El método AddNamedTable en IronXL requiere dos parámetros esenciales: el nombre de la tabla (como una cadena) y el objeto de rango que define el área de la tabla. Los parámetros opcionales incluyen showFilter (booleano) y tableStyle (de la enumeración TableStyles).

¿Puedo crear varias tablas con nombre y estilo en la misma hoja de cálculo?

Sí, IronXL le permite crear varias tablas con nombres y estilos diferentes en la misma hoja de cálculo. Cada tabla puede tener su propio nombre, rango, estilo y configuración de filtro, lo que la hace perfecta para organizar diferentes conjuntos de datos dentro de un único archivo de Excel.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,802,965 | Versión: 2025.12 recién lanzado