Como Adicionar Tabela Nomeada em Planilha Excel com C# e IronXL
Para adicionar uma tabela nomeada ao criar planilha 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.
-
Instale IronXL com o Gerenciador de Pacotes NuGet
PM > Install-Package IronXL.Excel -
Copie e execute este trecho de código.
var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXL.Styles.TableStyles.Medium2); -
Implante para testar em seu ambiente de produção.
Comece a usar IronXL em seu projeto hoje com uma avaliação gratuita
- Baixar a biblioteca C# para adicionar tabelas nomeadas
- Selecione o intervalo alvo com **`workSheet["A1:A5"]`**
- Utilize o método `AddNamedTable` para adicionar tabelas nomeadas
- Recuperar tabelas nomeadas de várias maneiras
- Exporte o arquivo Excel editado em vários formatos.
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");
' 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")
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");
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")
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);
}
' 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
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);
' 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)
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");
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")
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");
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")
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.

