Skip to footer content
USING IRONXL

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL

Working with Microsoft Excel files is a daily requirement for many .NET developers. Whether importing customer data, processing financial reports, or migrating data from spreadsheets or Excel workbooks to databases, developers need a reliable way to read Excel files or export Excel (XLSX) files without complex dependencies or requiring Excel to be installed. IronXL offers a straightforward solution that works across platforms, eliminating the need for Microsoft Office installation.

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 1 - IronXL

How Do I Get Started with C# Import Excel Data?

Getting started with Excel import in C# takes just minutes with IronXL. The Excel library handles both legacy XLS and modern XLSX formats seamlessly, along with CSV, TSV, and other spreadsheet formats. Unlike solutions that rely on Microsoft.Office.Interop.Excel, IronXL runs independently on any .NET or .NET Core platform.

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 2 - Cross Platform

First, install IronXL via NuGet Package Manager or select Manage NuGet packages in Visual Studio:

Install-Package IronXL.Excel

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 3 - Installation

Once installed, importing Excel data becomes remarkably simple:

using IronXL;
static void Main(string[] args)
{
 // Load any Excel file
 WorkBook workBook = WorkBook.Load("ProductData.xlsx");
 // Access the first worksheet
 WorkSheet sheet = workBook.WorkSheets[0];
 // Read a cell value
 string value = sheet["B1"].StringValue;
 Console.WriteLine(value);
}
using IronXL;
static void Main(string[] args)
{
 // Load any Excel file
 WorkBook workBook = WorkBook.Load("ProductData.xlsx");
 // Access the first worksheet
 WorkSheet sheet = workBook.WorkSheets[0];
 // Read a cell value
 string value = sheet["B1"].StringValue;
 Console.WriteLine(value);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code demonstrates the core workflow: loading a workbook, accessing a worksheet, and reading cell values. The WorkBook.Load() method automatically detects the file format, whether it's XLS, XLSX, or even CSV. The intuitive indexer syntax sheet["B1"] makes accessing cells as natural as working with arrays. For more complex operations, check the IronXL API reference for comprehensive documentation.

Sample Input

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 4 - Excel Input

Output

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 5 - Console Output

How Can I Read Excel Data into C# Objects?

Real applications need more than single-cell values. IronXL excels at importing entire datasets and converting them into usable C# objects. When you need to import Excel files with structured data, the library provides multiple approaches.

// Load the Excel file
WorkBook workBook = WorkBook.Load("ProductData.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Read a range of cells
 var products = new List<Product>();
 foreach (var row in sheet.Rows)
 {
     var product = new Product
     {
         Id = row.Columns[0].IntValue,
         Name = row.Columns[1].StringValue,
         Price = row.Columns[2].DecimalValue,
         IsAvailable = row.Columns[3].BoolValue
     };
     products.Add(product);
 }
 foreach (var product in products)
 {
     Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}, Available: {product.IsAvailable}");
 }
// Load the Excel file
WorkBook workBook = WorkBook.Load("ProductData.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Read a range of cells
 var products = new List<Product>();
 foreach (var row in sheet.Rows)
 {
     var product = new Product
     {
         Id = row.Columns[0].IntValue,
         Name = row.Columns[1].StringValue,
         Price = row.Columns[2].DecimalValue,
         IsAvailable = row.Columns[3].BoolValue
     };
     products.Add(product);
 }
 foreach (var product in products)
 {
     Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}, Available: {product.IsAvailable}");
 }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This example shows how to iterate through rows and map Excel data to strongly-typed C# objects. The typed properties like IntValue, StringValue, and DecimalValue handle type conversion automatically. This approach eliminates manual parsing and reduces errors when working with different data types. Many developers on Stack Overflow appreciate this type-safe approach to Excel data import.

Output

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 6 - Object Output

For more elegant data access, IronXL supports range operations:

// Read specific ranges of ProductData.xlsx file
Range dataRange = sheet["A1:D5"];
// Calculate aggregates directly
decimal sum = sheet["C1:C5"].Sum();
Console.WriteLine($"Sum of C1:C5: {sum}");
decimal max = sheet["C1:C5"].Max(c => c.DecimalValue);
Console.WriteLine($"Max of C1:C5: {max}");
// Use LINQ for filtering
var highValueOrders = dataRange
    .Where(cell => cell.DecimalValue > 100)
    .Select(cell => cell.Value)
    .ToList();
Console.WriteLine("High value orders (>100):");
// Print the high value orders to the console
foreach (var order in highValueOrders)
{
    Console.WriteLine(order);
}
// Read specific ranges of ProductData.xlsx file
Range dataRange = sheet["A1:D5"];
// Calculate aggregates directly
decimal sum = sheet["C1:C5"].Sum();
Console.WriteLine($"Sum of C1:C5: {sum}");
decimal max = sheet["C1:C5"].Max(c => c.DecimalValue);
Console.WriteLine($"Max of C1:C5: {max}");
// Use LINQ for filtering
var highValueOrders = dataRange
    .Where(cell => cell.DecimalValue > 100)
    .Select(cell => cell.Value)
    .ToList();
Console.WriteLine("High value orders (>100):");
// Print the high value orders to the console
foreach (var order in highValueOrders)
{
    Console.WriteLine(order);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The Range class provides collection-like access to multiple cells simultaneously. LINQ compatibility means developers can filter, transform, and aggregate Excel data using familiar C# patterns. The built-in aggregation methods, such as Sum() and Max(), operate directly on cell ranges without loading all data into memory first.

Output

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 7 - Range Output

How Do I Convert Excel to DataTable?

DataTable conversion is essential for database operations and data binding scenarios. IronXL provides built-in methods that efficiently handle the conversion from Excel to DataTable.This feature is particularly useful when you need to import Excel spreadsheets into SQL Server or other databases.

using System.Data;
// Load Excel file
WorkBook workBook = WorkBook.Load("inventory.xlsx");
// Select first Excel worksheet
WorkSheet sheet = workBook.WorkSheets.First();
// Convert to DataTable with headers
DataTable dataTable = sheet.ToDataTable(true);
// The DataTable is ready for database operations
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
{
    bulkCopy.DestinationTableName = "Inventory";
    bulkCopy.WriteToServer(dataTable);
}
using System.Data;
// Load Excel file
WorkBook workBook = WorkBook.Load("inventory.xlsx");
// Select first Excel worksheet
WorkSheet sheet = workBook.WorkSheets.First();
// Convert to DataTable with headers
DataTable dataTable = sheet.ToDataTable(true);
// The DataTable is ready for database operations
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
{
    bulkCopy.DestinationTableName = "Inventory";
    bulkCopy.WriteToServer(dataTable);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The ToDataTable() method accepts a boolean parameter indicating whether the first row contains headers. When set to true, IronXL automatically uses the first row values as column names in the DataTable. This DataTable integrates seamlessly with ADO.NET operations, Entity Framework, and data binding controls. Microsoft's documentation on SqlBulkCopy shows how efficiently this pattern handles large-scale data imports.

For more control over the conversion process:

// Custom DataTable conversion
DataTable customTable = new DataTable();
// Define columns based on Excel structure
for (int col = 0; col < sheet.ColumnCount; col++)
{
    customTable.Columns.Add($"Column{col + 1}", typeof(string));
}
// Import data with validation
foreach (var row in sheet.Rows)
{
    var dataRow = customTable.NewRow();
    for (int col = 0; col < sheet.ColumnCount; col++)
    {
        dataRow[col] = row.Columns[col].Value ?? DBNull.Value;
    }
    customTable.Rows.Add(dataRow);
}
// Print column headers
foreach (DataColumn column in customTable.Columns)
{
    Console.Write($"{column.ColumnName}\t");
}
Console.WriteLine();
// Print each row
foreach (DataRow row in customTable.Rows)
{
    foreach (var item in row.ItemArray)
    {
        Console.Write($"{item}\t");
    }
    Console.WriteLine();
}
// Custom DataTable conversion
DataTable customTable = new DataTable();
// Define columns based on Excel structure
for (int col = 0; col < sheet.ColumnCount; col++)
{
    customTable.Columns.Add($"Column{col + 1}", typeof(string));
}
// Import data with validation
foreach (var row in sheet.Rows)
{
    var dataRow = customTable.NewRow();
    for (int col = 0; col < sheet.ColumnCount; col++)
    {
        dataRow[col] = row.Columns[col].Value ?? DBNull.Value;
    }
    customTable.Rows.Add(dataRow);
}
// Print column headers
foreach (DataColumn column in customTable.Columns)
{
    Console.Write($"{column.ColumnName}\t");
}
Console.WriteLine();
// Print each row
foreach (DataRow row in customTable.Rows)
{
    foreach (var item in row.ItemArray)
    {
        Console.Write($"{item}\t");
    }
    Console.WriteLine();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach provides flexibility for data transformation during import. Null values are handled gracefully by converting them to DBNull.Value, ensuring compatibility with database operations.

Output

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 8 - DataTable Output

What Advanced Features Support Data Manipulation?

IronXL goes beyond basic reading with powerful features for complex scenarios. The library preserves Excel formulas, allowing calculations to update dynamically. For developers working with complex Excel workbooks, this maintains data integrity throughout the import process.

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 9 - Features

// Read calculated values from formulas
WorkSheet sheet = workBook.GetWorkSheet("Reports");
decimal calculatedTotal = sheet["E10"].DecimalValue; // Reads formula result
// Formulas remain intact
string formula = sheet["E10"].Formula; // Returns "=SUM(E2:E9)"
// Read calculated values from formulas
WorkSheet sheet = workBook.GetWorkSheet("Reports");
decimal calculatedTotal = sheet["E10"].DecimalValue; // Reads formula result
// Formulas remain intact
string formula = sheet["E10"].Formula; // Returns "=SUM(E2:E9)"
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Formula support means importing Excel files with complex calculations works without recreating business logic. The library evaluates formulas automatically, returning calculated values while preserving the original formula structure. This feature proves invaluable when you need to read Excel files containing financial models or reporting templates.

Cross-platform compatibility ensures consistent behavior across Windows, Linux, macOS, and container environments. This flexibility makes IronXL ideal for cloud deployments and microservices architectures where Office installation isn't feasible. The .NET Foundation's documentation highlights how modern .NET applications benefit from this platform independence when importing Excel data.

Entity Framework integration streamlines database workflows for C# Excel import scenarios:

var products = sheet.Rows.Skip(1)
    .Select(row => new Product
    {
        Name = row.Columns[0].StringValue,
        Price = row.Columns[1].DecimalValue
    })
    .ToList();
using (var context = new AppDbContext())
{
    context.Products.AddRange(products);
    await context.SaveChangesAsync();
}
var products = sheet.Rows.Skip(1)
    .Select(row => new Product
    {
        Name = row.Columns[0].StringValue,
        Price = row.Columns[1].DecimalValue
    })
    .ToList();
using (var context = new AppDbContext())
{
    context.Products.AddRange(products);
    await context.SaveChangesAsync();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This pattern enables direct Excel-to-database pipelines with minimal code, perfect for data migration and ETL processes. For comprehensive Excel manipulation capabilities, download IronXL to streamline your data import workflows.

Conclusion

IronXL transforms Excel data import from a complex challenge into straightforward C# code. The library's intuitive API, comprehensive format support, and cross-platform compatibility make it the practical choice for production applications requiring Excel file manipulation.

How to Easily Import, Read, and Manipulate MS Excel File Data in C# Using IronXL: Image 10 - Licensing

Ready to import Excel files into your C# projects? Start your free trial to explore IronXL's full capabilities. For detailed implementation guidance, visit the complete documentation or explore more Excel tutorials for advanced scenarios. For production deployments, view licensing options to find the right fit for your team.

Frequently Asked Questions

How can I import Excel data in C#?

You can use IronXL to import Excel data in C# easily, without needing Microsoft Excel installed on your system.

What are the benefits of using IronXL for Excel file manipulation?

IronXL allows developers to read, write, and manipulate Excel files in C# without complex dependencies, and it works across different platforms.

Do I need Microsoft Office installed to use IronXL?

No, IronXL eliminates the need for Microsoft Office installation, allowing you to work with Excel files directly within your C# applications.

Can IronXL handle both XLSX and CSV file formats?

Yes, IronXL supports various Excel file formats, including XLSX and CSV, making it versatile for different data processing needs.

Is IronXL suitable for processing large Excel files?

Yes, IronXL is designed to efficiently handle large Excel files, allowing developers to process extensive datasets without performance issues.

What platforms does IronXL support?

IronXL is compatible with multiple platforms, enabling cross-platform development and deployment of applications handling Excel files.

How does IronXL simplify data migration from Excel to databases?

IronXL provides straightforward methods to read and export data from Excel sheets, making it easier to transfer data to databases without complex coding.

Can I use IronXL to automate Excel report generation?

Yes, IronXL allows for the automation of Excel report generation, enabling you to programmatically create and manipulate Excel files in C#.

Is IronXL suitable for both small-scale and enterprise-level applications?

IronXL is versatile and scalable, making it suitable for both small-scale projects and large enterprise-level applications requiring Excel file manipulation.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More