Como adicionar tabela nomeada no Excel usando C#
Para adicionar uma tabela nomeada no Excel usando C#, use o método IronXL AddNamedTable com parâmetros para o nome da tabela, intervalo e estilo opcional — permitindo o gerenciamento estruturado de dados 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 em sua planilha usando IronXL—defina o nome, intervalo, visibilidade do filtro e estilo, tudo em uma chamada de método clara e única.
-
1Install IronXL with NuGet Package Manager
-
2Copie e execute este trecho de código.
var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXL.Styles.TableStyles.Medium2);C# -
3Implante para testar em seu ambiente de produção.
Comece a usar IronXL em seu projeto hoje com uma avaliação gratuita
Fluxo de trabalho mínimo (5 etapas)
- Baixar a biblioteca C# para adicionar tabelas nomeadas
- Selecione o intervalo alvo com workSheet["A1:A5"]
- Utilize o método
AddNamedTablepara 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 DataTable importar 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(TableStyle.TableStyleDark10);
namedTable.ShowFilter = true;
// Save the modified workbook
workbook.SaveAs("modified_example.xlsx");
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: TableStyle.TableStyleLight15);
// 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: TableStyle.TableStyleDark3);
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);
}Imports IronXL
' Load the Excel workbook
Dim workbook = WorkBook.Load("example.xlsx")
' Select the worksheet
Dim workSheet = workbook.WorkSheets.First()
' Retrieve all named table names
Dim tableNames = workSheet.GetNamedTableNames()
' Output each table name
For Each name In tableNames
Console.WriteLine("Named Table: " & name)
NextComo 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
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");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 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;
using IronXL.Styles;
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: TableStyle.TableStyleMedium9);
// 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");
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.
How do named tables in IronXL enhance data manipulation capabilities?
Named tables in IronXL offer powerful data manipulation capabilities. They allow for advanced operations like summing column values programmatically, adding summary rows, and applying conditional formatting, making them valuable for comprehensive Excel data management.
Can I integrate named tables with other features in IronXL?
Yes, named tables seamlessly integrate with other IronXL features. You can use them in conjunction with formulas for dynamic calculations, as data sources for creating charts, or as organized data structures before exporting to different formats.
How do I include formulas within a named table using IronXL?
When adding a named table with IronXL, you can include columns with formulas. For instance, you can calculate totals for each row based on other column values and then add grand total formulas below the data rows for comprehensive data analysis.
Where can I learn more about adding named ranges using IronXL?
You can learn more about adding named ranges in IronXL by visiting their documentation page on 'How to Add Named Range'. This section offers insights into creating and managing named ranges within Excel workbooks programmatically.

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 bem estruturados e visualmente atraentes.