Importuj plik Excel do DataTable z IronXL
C# Import Excel File into DataTable with IronXL
It's no secret that manually parsing Excel files is rarely the highlight of a developer's day. We've all been there, wrestling with legacy OLEDB connection strings or trying to map unstructured spreadsheet data into something your .NET application actually understands.
The DataTable in C# is the great equalizer. It acts as the perfect bridge, turning those rows and columns into a familiar structure ready for LINQ queries, DataGrid binding, or a quick trip to a SQL database.
IronXL takes the heavy lifting out of this process. Instead of complex configurations, it uses a single, intuitive ToDataTable method to handle the conversion. Whether you're building a reporting tool or a data migration script, here is how you can import Excel data effortlessly.
Want to follow along? Use the IronXL free trial to try this powerful library out for yourself.
How Can You Import an Excel File into a DataTable in C#?
To C# import Excel file into DataTable, load the workbook using WorkBook.Load, access the target worksheet, and call the ToDataTable method. This approach works with XLSX files, XLS, XLSM, and CSV formats. Ensure you reference the following namespaces to access the necessary classes.
Install IronXL via NuGet Package Manager the following command in Visual Studio using the NuGet Package Manager:
Install-Package IronXl.Excel
Then, use this concise code snippet to get your data moving:
using IronXL;
using System;
using System.Data;
class Program
{
static void Main(string[] args)
{
// Load the Excel file from the specified path
string filePath = "sales-data.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
// Access the first worksheet in the workbook
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable with first row as column headers
DataTable dt = worksheet.ToDataTable(true);
// Display the imported data
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(string.Join(" | ", row.ItemArray));
}
}
}
using IronXL;
using System;
using System.Data;
class Program
{
static void Main(string[] args)
{
// Load the Excel file from the specified path
string filePath = "sales-data.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
// Access the first worksheet in the workbook
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable with first row as column headers
DataTable dt = worksheet.ToDataTable(true);
// Display the imported data
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(string.Join(" | ", row.ItemArray));
}
}
}
Imports IronXL
Imports System
Imports System.Data
Module Program
Sub Main(args As String())
' Load the Excel file from the specified path
Dim filePath As String = "sales-data.xlsx"
Dim workbook As WorkBook = WorkBook.Load(filePath)
' Access the first worksheet in the workbook
Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
' Convert worksheet to DataTable with first row as column headers
Dim dt As DataTable = worksheet.ToDataTable(True)
' Display the imported data
For Each row As DataRow In dt.Rows
Console.WriteLine(String.Join(" | ", row.ItemArray))
Next
End Sub
End Module
Wynik

The WorkBook.Load method reads the Excel file from the string filePath location and creates a workbook object containing all Excel sheet data. The ToDataTable(true) parameter indicates that the first row contains column headers, which are automatically used as the Data Table column names.
What Is the Best Method for Reading Excel File Data into a DataTable?
Reading Excel file content efficiently requires handling both header rows and raw data scenarios. IronXL's ToDataTable method accepts a boolean parameter that determines whether the first row is treated as column names or as data. Note that handling extended properties or converting complex cell types may require additional configuration, but the default method handles most cases robustly.
using IronXL;
using System.Data;
// Load workbook from file path
string filePath = @"C:\Data\inventory.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
WorkSheet worksheet = workbook.WorkSheets[0];
// First row as headers (true) or as data (false)
DataTable dataTableWithHeaders = worksheet.ToDataTable(true);
DataTable dataTableWithoutHeaders = worksheet.ToDataTable(false);
// Process each row in the DataTable
foreach (DataRow row in dataTableWithHeaders.Rows)
{
for (int i = 0; i < dataTableWithHeaders.Columns.Count; i++)
{
object value = row[i];
Console.Write($"{value}\t");
}
Console.WriteLine();
}
using IronXL;
using System.Data;
// Load workbook from file path
string filePath = @"C:\Data\inventory.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
WorkSheet worksheet = workbook.WorkSheets[0];
// First row as headers (true) or as data (false)
DataTable dataTableWithHeaders = worksheet.ToDataTable(true);
DataTable dataTableWithoutHeaders = worksheet.ToDataTable(false);
// Process each row in the DataTable
foreach (DataRow row in dataTableWithHeaders.Rows)
{
for (int i = 0; i < dataTableWithHeaders.Columns.Count; i++)
{
object value = row[i];
Console.Write($"{value}\t");
}
Console.WriteLine();
}
Imports IronXL
Imports System.Data
' Load workbook from file path
Dim filePath As String = "C:\Data\inventory.xlsx"
Dim workbook As WorkBook = WorkBook.Load(filePath)
Dim worksheet As WorkSheet = workbook.WorkSheets(0)
' First row as headers (true) or as data (false)
Dim dataTableWithHeaders As DataTable = worksheet.ToDataTable(True)
Dim dataTableWithoutHeaders As DataTable = worksheet.ToDataTable(False)
' Process each row in the DataTable
For Each row As DataRow In dataTableWithHeaders.Rows
For i As Integer = 0 To dataTableWithHeaders.Columns.Count - 1
Dim value As Object = row(i)
Console.Write($"{value}" & vbTab)
Next
Console.WriteLine()
Next
Wynik

This flexibility makes IronXL ideal for processing Excel spreadsheet files regardless of their structure. Unlike the EPPlus package or traditional methods requiring new OleDbDataAdapter instances, IronXL handles the conversion in a single method call. The library supports .NET Core, .NET Framework, and cross-platform deployment without requiring Microsoft Excel installation.
How Do You Convert Multiple Excel Worksheets to a DataSet?
When your Excel workbook contains multiple sheets, converting to a DataSet preserves each Excel worksheet as a separate DataTable within the collection. This approach is essential for reporting applications and multi-sheet data processing.
using IronXL;
using System;
using System.Data;
// Load multi-sheet workbook
WorkBook workbook = WorkBook.Load("quarterly-reports.xlsx");
// Convert entire workbook to DataSet (each sheet becomes a DataTable)
DataSet dataset = workbook.ToDataSet();
// Iterate through all tables in the DataSet
foreach (DataTable table in dataset.Tables)
{
Console.WriteLine($"Sheet: {table.TableName}");
Console.WriteLine($"Rows: {table.Rows.Count}, Columns: {table.Columns.Count}");
foreach (DataRow row in table.Rows)
{
Console.WriteLine(string.Join(", ", row.ItemArray));
}
}
using IronXL;
using System;
using System.Data;
// Load multi-sheet workbook
WorkBook workbook = WorkBook.Load("quarterly-reports.xlsx");
// Convert entire workbook to DataSet (each sheet becomes a DataTable)
DataSet dataset = workbook.ToDataSet();
// Iterate through all tables in the DataSet
foreach (DataTable table in dataset.Tables)
{
Console.WriteLine($"Sheet: {table.TableName}");
Console.WriteLine($"Rows: {table.Rows.Count}, Columns: {table.Columns.Count}");
foreach (DataRow row in table.Rows)
{
Console.WriteLine(string.Join(", ", row.ItemArray));
}
}
Imports IronXL
Imports System
Imports System.Data
' Load multi-sheet workbook
Dim workbook As WorkBook = WorkBook.Load("quarterly-reports.xlsx")
' Convert entire workbook to DataSet (each sheet becomes a DataTable)
Dim dataset As DataSet = workbook.ToDataSet()
' Iterate through all tables in the DataSet
For Each table As DataTable In dataset.Tables
Console.WriteLine($"Sheet: {table.TableName}")
Console.WriteLine($"Rows: {table.Rows.Count}, Columns: {table.Columns.Count}")
For Each row As DataRow In table.Rows
Console.WriteLine(String.Join(", ", row.ItemArray))
Next
Next
Wynik

The ToDataSet method creates a new DataSet containing DataTable objects for every worksheet. Each table's TableName property reflects the original Excel sheet name, making it easy to reference specific data during processing.
How Can You Import Data from Excel to a Database?
A common workflow involves reading Excel file data and inserting it into a database system. The DataTable structure integrates seamlessly with ADO.NET for database operations.
using IronXL;
using System.Data;
using System.Data.SqlClient;
string filePath = @"C:\imports\customer-data.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Convert Excel data to DataTable
DataTable dt = worksheet.ToDataTable(true);
// Validate data before database insert
if (dt == null || dt.Rows.Count == 0)
{
Console.WriteLine("No data to import");
return;
}
// Insert into database using SqlBulkCopy
string connectionString = "Server=.;Database=Sales;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = "Customers";
bulkCopy.WriteToServer(dt);
}
}
Console.WriteLine($"Imported {dt.Rows.Count} records successfully");
using IronXL;
using System.Data;
using System.Data.SqlClient;
string filePath = @"C:\imports\customer-data.xlsx";
WorkBook workbook = WorkBook.Load(filePath);
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Convert Excel data to DataTable
DataTable dt = worksheet.ToDataTable(true);
// Validate data before database insert
if (dt == null || dt.Rows.Count == 0)
{
Console.WriteLine("No data to import");
return;
}
// Insert into database using SqlBulkCopy
string connectionString = "Server=.;Database=Sales;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = "Customers";
bulkCopy.WriteToServer(dt);
}
}
Console.WriteLine($"Imported {dt.Rows.Count} records successfully");
Imports IronXL
Imports System.Data
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim filePath As String = "C:\imports\customer-data.xlsx"
Dim workbook As WorkBook = WorkBook.Load(filePath)
Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
' Convert Excel data to DataTable
Dim dt As DataTable = worksheet.ToDataTable(True)
' Validate data before database insert
If dt Is Nothing OrElse dt.Rows.Count = 0 Then
Console.WriteLine("No data to import")
Return
End If
' Insert into database using SqlBulkCopy
Dim connectionString As String = "Server=.;Database=Sales;Trusted_Connection=True;"
Using connection As New SqlConnection(connectionString)
connection.Open()
Using bulkCopy As New SqlBulkCopy(connection)
bulkCopy.DestinationTableName = "Customers"
bulkCopy.WriteToServer(dt)
End Using
End Using
Console.WriteLine($"Imported {dt.Rows.Count} records successfully")
End Sub
End Module
This code demonstrates how to load an Excel file, convert it to a DataTable, and perform a bulk database insert. The null check ensures data integrity before attempting the import operation.
How Do You Export a DataTable Back to Excel?
IronXL supports bi-directional data flow, allowing you to create Excel files from DataTable objects for reporting and data export scenarios.
using IronXL;
using System.Data;
// Create sample DataTable
DataTable dt = new DataTable("Products");
dt.Columns.Add("ProductID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Rows.Add(1, "Widget", 29.99m);
dt.Rows.Add(2, "Gadget", 49.99m);
// Create new workbook and load DataTable
WorkBook workbook = WorkBook.Create();
workbook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } });
// Save as Excel file
workbook.SaveAs("exported-products.xlsx");
using IronXL;
using System.Data;
// Create sample DataTable
DataTable dt = new DataTable("Products");
dt.Columns.Add("ProductID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Rows.Add(1, "Widget", 29.99m);
dt.Rows.Add(2, "Gadget", 49.99m);
// Create new workbook and load DataTable
WorkBook workbook = WorkBook.Create();
workbook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } });
// Save as Excel file
workbook.SaveAs("exported-products.xlsx");
Imports IronXL
Imports System.Data
' Create sample DataTable
Dim dt As New DataTable("Products")
dt.Columns.Add("ProductID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Price", GetType(Decimal))
dt.Rows.Add(1, "Widget", 29.99D)
dt.Rows.Add(2, "Gadget", 49.99D)
' Create new workbook and load DataTable
Dim workbook As WorkBook = WorkBook.Create()
workbook.LoadWorkSheetsFromDataSet(New DataSet With {.Tables = {dt}})
' Save as Excel file
workbook.SaveAs("exported-products.xlsx")
Wynik

The LoadWorkSheetsFromDataSet method accepts a DataSet containing your DataTable objects and creates corresponding worksheets. Learn more about exporting DataTable to Excel in the documentation.
Wnioski
IronXL transforms the complexity of Excel-to-DataTable conversion into straightforward method calls. Whether importing a single Excel worksheet or processing multi-sheet workbooks into a complete DataSet, the library handles XLSX files, data type conversion, and stream-based loading efficiently.
The combination of DataTable flexibility and IronXL's intuitive API enables powerful data workflows for database integration, reporting systems, and application data binding. Download IronXL to streamline your Excel data processing, or purchase a license for production deployment.
Często Zadawane Pytania
Jak zaimportować plik Excel do tabeli danych (DataTable) przy użyciu języka C#?
Za pomocą IronXL można łatwo importować pliki Excel do tabeli danych (DataTable) w języku C#. IronXL udostępnia proste API do ładowania plików Excel i konwertowania ich na tabele danych w celu dalszej obróbki.
Jakie są zalety korzystania z IronXL do manipulacji plikami Excel w języku C#?
IronXL oferuje solidne rozwiązanie do manipulowania plikami Excel w języku C#, w tym odczytu, zapisu i konwersji danych Excel do różnych formatów, takich jak DataTables. Obsługuje wszystkie główne typy plików Excel i zapewnia wysoką wydajność oraz łatwość użytkowania.
Czy IronXL jest kompatybilny z .NET Core?
Tak, IronXL jest w pełni kompatybilny z .NET Core, umożliwiając wieloplatformowe tworzenie i wdrażanie aplikacji wymagających manipulacji plikami Excel.
Czy mogę używać IronXL do odczytu plików Excel w różnych formatach?
IronXL obsługuje odczyt plików Excel w różnych formatach, w tym XLSX, XLS, CSV i TSV, oferując elastyczność w obsłudze różnych typów danych Excel.
Czy IronXL obsługuje funkcje zabezpieczeń plików Excel?
Tak, IronXL obsługuje pliki Excel chronione hasłem, umożliwiając ładowanie i pracę z zabezpieczonymi dokumentami Excel w aplikacjach C#.
Jak przekonwertować plik Excel na tabelę danych (DataTable) za pomocą IronXL?
Dzięki IronXL można przekonwertować plik Excel na tabelę danych (DataTable), ładując skoroszyt, wybierając arkusz i wykorzystując wbudowane metody do eksportowania danych arkusza do tabeli danych.
Jakie rodzaje aplikacji mogą skorzystać z użycia IronXL?
IronXL idealnie nadaje się do wszelkich aplikacji wymagających manipulacji danymi programu Excel, takich jak narzędzia do analizy danych, systemy raportowania lub dowolne oprogramowanie, które musi importować, eksportować lub modyfikować dane programu Excel.
Czy IronXL może służyć do edycji plików Excel po zaimportowaniu ich do DataTable?
Tak, IronXL pozwala edytować i aktualizować pliki Excel nawet po zaimportowaniu ich do DataTable, zapewniając płynne wprowadzanie i zapisywanie zmian.
Jakie doświadczenie w programowaniu jest potrzebne do korzystania z IronXL?
IronXL został zaprojektowany z myślą o łatwości użytkowania i posiada przyjazny dla użytkownika interfejs API, z którego mogą korzystać programiści o każdym poziomie doświadczenia, dzięki czemu jest dostępny zarówno dla początkujących, jak i zaawansowanych użytkowników.




