Como adicionar uma tabela nomeada no Excel usando C# | IronXL

Como adicionar tabela nomeada no Excel usando C

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

Para adicionar uma tabela nomeada no Excel usando C#, use o método AddNamedTable do IronXL com parâmetros para o nome da tabela, intervalo e estilo opcional, permitindo a gestão de dados estruturados com uma única chamada de método.

Uma tabela nomeada também é comumente conhecida como Tabela do Excel, que se refere a um tipo específico de intervalo que foi designado com um nome e tem funcionalidades e propriedades adicionais associadas. Tabelas nomeadas fornecem capacidades aprimoradas de organização de dados, formatação automática, filtragem incorporada e integração perfeita com fórmulas do Excel—tornando-se essenciais para gerenciar conjuntos de dados estruturados em fluxos de trabalho de automação do Excel.

Introdução rápida: criar e nomear uma tabela em uma linha

Este exemplo mostra como você pode adicionar facilmente uma tabela nomeada na sua planilha usando o IronXL—defina o nome, intervalo, visibilidade do filtro e estilo tudo em uma única e clara chamada de método.

  1. Instale IronXL com o Gerenciador de Pacotes NuGet

    PM > Install-Package IronXl.Excel
  2. Copie e execute este trecho de código.

    var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXl.Styles.TableStyles.Medium2);
  3. Implante para testar em seu ambiente de produção.

    Comece a usar IronXL em seu projeto hoje com uma avaliação gratuita

    arrow pointer


Como adiciono uma tabela nomeada na minha planilha do Excel?

Para adicionar uma tabela nomeada, use o método AddNamedTable. O método requer o nome da tabela como uma string e o objeto de intervalo. Você também tem a opção de especificar o estilo da tabela e se deseja mostrar o filtro. Esta funcionalidade é particularmente útil ao trabalhar com DataSet e importações DataTable onde os dados estruturados precisam de organização adequada.

// 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

As tabelas nomeadas suportam várias opções de estilo através da enumeração TableStyles. Você pode aplicar formatação profissional instantaneamente, que complementa outros recursos de formatação como estilo e bordas de células. Aqui está um exemplo demonstrando diferentes aplicações de estilo de tabela:

// 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
Planilha do Excel mostrando uma tabela nomeada com três colunas e cabeçalhos formatados contendo dados de texto de amostra

Como posso recuperar tabelas nomeadas da minha planilha?

Qual método retorna todas as tabelas nomeadas em uma planilha?

O método GetNamedTableNames retorna todas as tabelas nomeadas na planilha como uma lista de strings. Isso é particularmente útil ao trabalhar com planilhas que contêm várias tabelas ou ao gerenciar planilhas com estruturas de dados 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

Como eu acesso uma tabela nomeada específica pelo seu nome?

Use o método GetNamedTable para recuperar uma tabela nomeada específica na planilha. Depois de recuperada, você pode acessar várias propriedades e realizar operações como ordenar intervalos de células ou aplicar formatação 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

Trabalhando com Dados de Tabelas

Tabelas nomeadas oferecem poderosas capacidades de manipulação de dados. Aqui está um exemplo completo mostrando como trabalhar com dados de tabela:

// 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

Integração com Outros Recursos do IronXL

Tabelas nomeadas funcionam perfeitamente com outros recursos do IronXL. Você pode combiná-las com fórmulas para cálculos dinâmicos ou usá-las como fontes de dados ao criar gráficos. Elas também são excelentes para organizar dados antes de exportar para formatos diferentes.

// 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

O IronXL também pode adicionar intervalos nomeados. Saiba mais em Como Adicionar Intervalo Nomeado.

Perguntas frequentes

O que é uma tabela nomeada no Excel?

Uma tabela nomeada no Excel é um tipo específico de intervalo que recebeu um nome e inclui funcionalidades adicionais. O IronXL permite criar essas tabelas programaticamente em C#, oferecendo recursos aprimorados de organização de dados, formatação automática, filtragem integrada e integração perfeita com fórmulas do Excel.

Como adiciono uma tabela nomeada a uma planilha do Excel usando C#?

Para adicionar uma tabela nomeada usando o IronXL, utilize o método `AddNamedTable`. Este método requer o nome da tabela como uma string e um objeto de intervalo. Opcionalmente, você pode especificar o estilo da tabela e a visibilidade do filtro. Por exemplo: `workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXl.Styles.TableStyles.Medium2).`

Posso aplicar estilos personalizados a tabelas nomeadas?

Sim, o IronXL oferece suporte a várias opções de estilo para tabelas nomeadas por meio da enumeração `TableStyles`. Você pode aplicar formatação profissional instantaneamente usando estilos como `Dark10`, `Medium2` e outros estilos de tabela predefinidos. Basta usar o método `SetStyle` ou especificar o parâmetro `tableStyle` ao criar a tabela.

É possível mostrar ou ocultar filtros em tabelas nomeadas?

Com certeza! O IronXL permite controlar a visibilidade dos filtros em tabelas nomeadas. Você pode definir a propriedade ShowFilter como true ou false, ou especificá-la diretamente ao criar a tabela usando o parâmetro showFilter no método AddNamedTable.

Quais são os parâmetros necessários para criar uma tabela nomeada?

O método AddNamedTable no IronXL requer dois parâmetros essenciais: o nome da tabela (como uma string) e o objeto range que define a área da tabela. Parâmetros opcionais incluem showFilter (booleano) e tableStyle (da enumeração TableStyles).

Posso criar várias tabelas nomeadas e estilizadas na mesma planilha?

Sim, o IronXL permite criar várias tabelas nomeadas com estilos diferentes na mesma planilha. Cada tabela pode ter seu próprio nome, intervalo, estilo e configurações de filtro exclusivos, tornando-o perfeito para organizar diferentes conjuntos de dados em um único arquivo do Excel.

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 12
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 19
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Pronto para começar?
Nuget Downloads 1,890,100 | Versão: 2026.3 acaba de ser lançado

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 17
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 24
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas? PM > Install-Package IronXl.Excel
executar um exemplo Veja seus dados se transformarem em uma planilha.