Jak dodać tabelę nazwaną w programie Excel przy użyciu języka C
Aby dodać tabelę o nazwie w Excelu używając C#, użyj metody IronXL AddNamedTable z parametrami dla nazwy tabeli, zakresu oraz opcjonalnego stylowania — umożliwia to zarządzanie danymi strukturalnymi jednym wywołaniem metody.
Tabela nazwana jest również powszechnie znana jako tabela Excel, co odnosi się do określonego typu zakresu, który został oznaczony nazwą i ma przypisane dodatkowe funkcje oraz właściwości. Tabele nazwane zapewniają rozszerzone możliwości organizacji danych, automatyczne formatowanie, wbudowane filtrowanie oraz płynną integrację z formułami programu Excel — dzięki czemu są niezbędne do zarządzania ustrukturyzowanymi zbiorami danych w procesach automatyzacji w programie Excel.
Szybki start: Utwórz i nazwij tabelę w jednym wierszu
Ten przykład pokazuje, jak łatwo można dodać tabelę o nazwie w arkuszu za pomocą IronXL — zdefiniuj nazwę, zakres, widoczność filtrów i styl za pomocą jednego, przejrzystego wywołania metody.
-
Install IronXL with NuGet Package Manager
PM > Install-Package IronXl.Excel -
Skopiuj i uruchom ten fragment kodu.
var table = workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXl.Styles.TableStyles.Medium2); -
Wdrożenie do testowania w środowisku produkcyjnym
Rozpocznij używanie IronXL w swoim projekcie już dziś z darmową wersją próbną
Minimalny proces (5 kroków)
- Pobierz bibliotekę C#, aby dodać tabele nazwane
- Wybierz zakres docelowy za pomocą
workSheet["A1:A5"] - Użyj metody
AddNamedTable,aby dodać tabele nazwane - Pobieranie nazwanych tabel na różne sposoby
- Eksportuj edytowany plik Excel w różnych formatach
Jak dodać tabelę o nazwie do arkusza Excel?
Aby dodać tabelę o nazwie, użyj metody AddNamedTable. Metoda wymaga nazwy tabeli jako ciągu znaków oraz obiektu zakresu. Możesz również określić styl tabeli oraz zdecydować, czy wyświetlać filtr. Ta funkcjonalność jest szczególnie przydatna przy pracy z DataSet i DataTable importami, gdzie strukturalne dane wymagają odpowiedniej organizacji.
// 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");
Imports IronXL
Imports IronXl.Styles
' Load the Excel workbook
Dim workbook = WorkBook.Load("example.xlsx")
' Select the worksheet
Dim workSheet = workbook.WorkSheets.First()
' Define the range for the named table
Dim range = workSheet("A1:B10")
' Add a named table with the specified name and range
Dim 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")
Nazwane tabele obsługują różne opcje stylizacji poprzez wyliczenie TableStyles. Możesz natychmiast zastosować Professional formatowanie, które uzupełnia inne funkcje formatowania, takie jak stylizacja komórek i obramowania. Oto przykład ilustrujący różne zastosowania stylów tabel:
// 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
Module Module1
Sub Main()
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")
End Sub
End Module
Jak mogę pobrać nazwane tabele z mojego arkusza?
Jaka metoda zwraca wszystkie nazwane tabele w arkuszu?
Metoda GetNamedTableNames zwraca wszystkie nazwane tabele w arkuszu jako listę ciągów znaków. Jest to szczególnie przydatne podczas pracy z skoroszytami zawierającymi wiele tabel lub podczas zarządzania arkuszami z dynamicznymi strukturami danych.
// 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
Jak uzyskać dostęp do konkretnej tabeli o określonej nazwie?
Użyj metody GetNamedTable, aby pobrać konkretną nazwaną tabelę w arkuszu. Po pobraniu danych można uzyskać dostęp do różnych właściwości i wykonywać operacje, takie jak sortowanie zakresów komórek lub stosowanie formatowania warunkowego.
// 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)
Praca z danymi tabelarycznymi
Tabele nazwane zapewniają zaawansowane możliwości manipulacji danymi. Oto obszerny przykład pokazujący, jak pracować z danymi tabelarycznymi:
// 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")
Integracja z innymi funkcjami IronXL
Tabele nazwane płynnie współpracują z innymi funkcjami IronXL. Można je łączyć z formułami do obliczeń dynamicznych lub wykorzystywać jako źródła danych podczas tworzenia wykresów. Świetnie nadają się również do porządkowania danych przed eksportem do różnych formatów.
// 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")
IronXL może również dodawać nazwane zakresy. Dowiedz się więcej w artykule Jak dodać nazwany zakres.
Często Zadawane Pytania
Co to jest nazwana tabela w Excelu?
Nazwana tabela w Excelu to określony typ zakresu, który został oznaczony nazwą i zawiera dodatkowe funkcje. IronXL umożliwia programowe tworzenie tych tabel w C#, oferując lepsze możliwości organizacji danych, automatyczne formatowanie, wbudowane filtrowanie i bezproblemową integrację z formułami Excela.
Jak dodać nazwaną tabelę do arkusza Excela używając C#?
Aby dodać nazwaną tabelę za pomocą IronXL, użyj metody AddNamedTable. Ta metoda wymaga nazwy tabeli jako tekstu oraz obiektu zakresu. Można opcjonalnie określić styl tabeli i widoczność filtrów. Na przykład: workSheet.AddNamedTable("MyTable", workSheet.GetRange("A1:B5"), showFilter: true, tableStyle: IronXl.Styles.TableStyles.Medium2).
Czy mogę zastosować własne style do nazwanych tabel?
Tak, IronXL obsługuje różne opcje stylizacji dla nazwanych tabel za pomocą wyliczenia TableStyles. Można natychmiast zastosować profesjonalne formatowanie korzystając ze stylów takich jak Dark10, Medium2 i innych predefiniowanych stylów tabel. Wystarczy użyć metody SetStyle lub określić parametr tableStyle podczas tworzenia tabeli.
Czy mogę pokazać lub ukryć filtry w nazwanych tabelach?
Absolutnie! IronXL pozwala kontrolować widoczność filtrów w nazwanych tabelach. Można ustawić właściwość ShowFilter na true lub false, lub określić ją bezpośrednio podczas tworzenia tabeli używając parametru showFilter w metodzie AddNamedTable.
Jakie są wymagane parametry do stworzenia nazwanej tabeli?
Metoda AddNamedTable w IronXL wymaga dwóch podstawowych parametrów: nazwy tabeli (jako tekst) i obiektu zakresu definiującego obszar tabeli. Opcjonalne parametry to showFilter (boolean) i tableStyle (z wyliczenia TableStyles).
Czy mogę stworzyć wielokrotne stylizowane nazwane tabele w tym samym arkuszu roboczym?
Tak, IronXL pozwala tworzyć wiele nazwanych tabel z różnymi stylami w tym samym arkuszu. Każda tabela może mieć własną unikalną nazwę, zakres, styl i ustawienia filtrów, co doskonale nadaje się do organizacji różnych zestawów danych w jednym pliku Excela.

