In .NET enterprise development, converting Excel files to DataTable objects is a common requirement. DataTable serves as a versatile in-memory data structure for subsequent validation, persistance, and presentation operations.
Install the Free Spire.XLS for .NET library via NuGet Package Manager:
- Right-click project → Manage NuGet Packages
- Search for the library and install the latest stable version
- Or execute in Package Manager Console:
Install-Package FreeSpire.XLS
Note: The free version has data volume limitations suitable for small-scale processing.
Core Implementation: Excel to DataTable
Basic Conversion Process
This code demonstrates the complete conversion workflow from Excel file to DataTable:
using Spire.Xls;
using System;
using System.Data;
namespace ExcelConverter
{
class DataProcessor
{
static void ExecuteConversion()
{
string sourceFile = "DataFile.xlsx";
// Initialize workbook and load Excel file
Workbook excelBook = new Workbook();
excelBook.LoadFromFile(sourceFile);
// Access first worksheet
Worksheet dataSheet = excelBook.Worksheets[0];
// Convert worksheet data to DataTable
// First parameter: cell range containing data
// Second parameter: use first row as column headers
DataTable resultTable = dataSheet.ExportDataTable(
dataSheet.AllocatedRange,
true
);
// Display conversion results
Console.WriteLine("=== Excel to DataTable Results ===");
Console.WriteLine($"Total data rows: {resultTable.Rows.Count}");
Console.Write("Column names: ");
foreach (DataColumn column in resultTable.Columns)
{
Console.Write(column.ColumnName + "\t");
}
Console.WriteLine("\n=== Data Content ===");
foreach (DataRow record in resultTable.Rows)
{
foreach (object field in record.ItemArray)
{
Console.Write(field + "\t");
}
Console.WriteLine();
}
}
}
}
Advanced Conversion Scenarios
ExportDataTable provides overloaded methods for customized conversion requirements:
Scenario 1: Convert Specific Cell Range
// Define specific cell range (rows 2-10, columns A-C)
CellRange selectedCells = dataSheet.Range["A2:C10"];
// Convert without using first row as headers
DataTable resultTable = dataSheet.ExportDataTable(selectedCells, false);
Scenario 2: Convert with Formula Evaluation
// Overload method with formula calculation
// Parameters:
// range: target cell range
// useHeaders: first row as column names
// computeFormulas: evaluate formula results
DataTable resultTable = dataSheet.ExportDataTable(
dataSheet.AllocatedRange,
true,
true
);
The ExportDataTable method efficiently handles Excel to DataTable conversion by encapsulating cell iteration and type mapping logic, replacing manual cell-by-cell processing.