Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
Working with Excel files programmatically can significantly enhance the efficiency and automation capabilities of your C# applications. Whether you're generating reports, processing data, or creating complex spreadsheets dynamically, mastering the manipulation of Excel files is crucial. In this tutorial, we will focus on working with Excel ranges using IronXL. We'll cover how to write, read, and manipulate ranges within an Excel file.
IronXL is a comprehensive library for C# that simplifies working with Excel files, offering a range of features for seamless integration and manipulation of spreadsheet data. Its capabilities include reading, writing, and modifying Excel files without requiring Microsoft Excel installation, enabling cross-platform compatibility.
IronXL facilitates the extraction of data from specific cells, ranges, or entire worksheets, along with advanced functionalities such as formatting, styling, and conditional formatting. With support for calculations, formulas, and statistical analysis, IronXL empowers developers to efficiently handle Excel operations programmatically, making it an indispensable tool for automating data-centric tasks within C# applications.
First of all, we need to install the IronXL Library in our Application.
You can install IronXL via the NuGet Package Manager with the following command:
Install-Package IronXL.Excel
Install-Package IronXL.Excel
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronXL.Excel
The above command will install IronXL with all its dependencies.
Add the following namespace at the top of the Program.cs class, or wherever you want to use IronXL methods.
using IronXL;
using IronXL;
Imports IronXL
The very first step is to load the Excel workbook. The following code will load the Excel workbook in our application.
static void Main(string[] args)
{
var workbook = WorkBook.Load("test_excel.xlsx");
var sheet = workbook.GetWorkSheet("Sheet1");
}
static void Main(string[] args)
{
var workbook = WorkBook.Load("test_excel.xlsx");
var sheet = workbook.GetWorkSheet("Sheet1");
}
Shared Sub Main(ByVal args() As String)
Dim workbook = WorkBook.Load("test_excel.xlsx")
Dim sheet = workbook.GetWorkSheet("Sheet1")
End Sub
The file line loads an existing Excel workbook from the file named "test_excel.xlsx". The second line retrieves the worksheet named "Sheet1" from the loaded workbook.
I will be using the following Excel file throughout this tutorial.
Now, let's read data from specified cell ranges.
var range = sheet["A2:G10"];
foreach (var item in range)
{
Console.WriteLine(item);
}
var range = sheet["A2:G10"];
foreach (var item in range)
{
Console.WriteLine(item);
}
Dim range = sheet("A2:G10")
For Each item In range
Console.WriteLine(item)
Next item
The first line selects a specific range address (A2 to G10) in the worksheet, allowing you to work with multiple Excel cells simultaneously. The foreach (var item in range) loop iterates over each cell within this cell range, enabling efficient data processing.
By using Console.WriteLine(item); the code prints each cell's value to the console, making it easy to review the contents of the range. This approach simplifies data handling and improves code readability.
Let's select a specific range, and implement some Excel formulas.
var range = sheet["F2:F42"];
Console.WriteLine($"Minimum Age: {range.Min()}");
Console.WriteLine($"Maximum Age: {range.Max()}");
Console.WriteLine($"Average Age: {(int)range.Avg()}");
var range = sheet["F2:F42"];
Console.WriteLine($"Minimum Age: {range.Min()}");
Console.WriteLine($"Maximum Age: {range.Max()}");
Console.WriteLine($"Average Age: {(int)range.Avg()}");
Imports System
Dim range = sheet("F2:F42")
Console.WriteLine($"Minimum Age: {range.Min()}")
Console.WriteLine($"Maximum Age: {range.Max()}")
Console.WriteLine($"Average Age: {CInt(Math.Truncate(range.Avg()))}")
The code var range = sheet["F2:F42"]; selects a range of cells spanning from F2 to F42, facilitating statistical analysis of age data. Using range.Min() and range.Max(), it efficiently calculates the minimum and maximum age values within the specified range, aiding in demographic insights.
Additionally, range.Avg() computes the average age, offering valuable statistical metrics for data interpretation. This approach simplifies data analysis tasks, providing quick access to essential statistical information for informed decision-making.
Let's read data from a single cell.
var read_from_single_cell = sheet["B2"];
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");
var read_from_single_cell = sheet["B2"];
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");
Dim read_from_single_cell = sheet("B2")
Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}")
The code var read_from_single_cell = sheet["B2"]; retrieves the value stored in cell B2 from the worksheet. Using this approach, you can easily access specific cell values within the Excel file.
With Console.WriteLine($"The Value in Cell B2 is: {read_from_single_cell}");, the code prints the retrieved value of referencing cells to the console, facilitating data verification and debugging. This simplifies the process of retrieving and displaying individual cell values from Excel files.
Let's Read Data from an entire column using Index.
// Get Last name Column from Index 2
var columnValues = sheet.GetColumn(2); // 2 is column index
foreach ( var columnValue in columnValues )
{
Console.WriteLine(columnValue);
}
// Get Last name Column from Index 2
var columnValues = sheet.GetColumn(2); // 2 is column index
foreach ( var columnValue in columnValues )
{
Console.WriteLine(columnValue);
}
' Get Last name Column from Index 2
Dim columnValues = sheet.GetColumn(2) ' 2 is column index
For Each columnValue In columnValues
Console.WriteLine(columnValue)
Next columnValue
The code var columnValues = sheet.GetColumn(2); retrieves all values from the column located at index 2 (B column) in the worksheet. This allows you to efficiently access all values within a specific column of the Excel sheet.
Through the foreach loop iterating over columnValues, each value in the column is printed to the console using Console.WriteLine(columnValue);. This approach facilitates processing and displaying columnar data from Excel files, streamlining data analysis tasks.
Alternatively, we can also read data from a column using a Column Name instead of an index. Consider the following example:
var columnValues = sheet.GetColumn("C");
var columnValues = sheet.GetColumn("C");
Dim columnValues = sheet.GetColumn("C")
In this way, we can specify several columns.
Let's Read data from the entire row by using row numbers.
var rowValues = sheet.GetRow(1);// 1 is row index
foreach (var rowValue in rowValues)
{
Console.Write(rowValue + " ");
}
var rowValues = sheet.GetRow(1);// 1 is row index
foreach (var rowValue in rowValues)
{
Console.Write(rowValue + " ");
}
Dim rowValues = sheet.GetRow(1) ' 1 is row index
For Each rowValue In rowValues
Console.Write(rowValue & " ")
Next rowValue
The code var rowValues = sheet.GetRow(1); retrieves all values from a single row located at index 1 (Row 2) in the worksheet, enabling efficient access to row-specific data. Through the foreach loop iterating over rowValues, each value in the row is printed to the console using Console.Write(rowValue + " ");.
This approach simplifies the extraction and display of row data from Excel files, aiding in data analysis and reporting tasks. In this way, we can read values from multiple cells without range specification.
We can write data to both cell and range. First of all, we will write data to a range.
var range = sheet["D2:D14"];
range.Value = "Prefer Not to Say"; // Change Gender Value
workbook.Save();
var range = sheet["D2:D14"];
range.Value = "Prefer Not to Say"; // Change Gender Value
workbook.Save();
Dim range = sheet("D2:D14")
range.Value = "Prefer Not to Say" ' Change Gender Value
workbook.Save()
The code var range = sheet["D2:D14"]; selects a range spanning from cell D2 to D14, enabling bulk data modification. By setting range.Value to "Prefer Not to Say", it efficiently updates the gender value for each cell within the specified range, minimizing repetitive tasks.
The subsequent workbook.Save(); command ensures persistent storage of these changes, maintaining data consistency and integrity. This approach simplifies batch updates and ensures uniformity across multiple cells, enhancing data management efficiency.
Now, Let's write data to a specific cell.
sheet["B2"].Value = "John";
workbook.Save();
sheet["B2"].Value = "John";
workbook.Save();
sheet("B2").Value = "John"
workbook.Save()
The code sheet["B2"].Value = "John"; directly assigns the value "John" to cell B2 in the Excel worksheet, offering a concise and straightforward method for updating specific cell values. This approach streamlines the process of modifying individual cell contents, improving code readability and efficiency.
In conclusion, mastering Excel range operations in C# using IronXL significantly enhances the efficiency and automation capabilities of applications, facilitating tasks such as data processing, report generation, and dynamic spreadsheet creation.
With IronXL's powerful features for reading, writing, and manipulating Excel files, developers can streamline data handling processes and leverage advanced functionalities like formulas, formatting, and statistical analysis. Additionally, IronXL offers a free trial, ensuring flexibility and scalability for various project requirements.
9 .NET API products for your office documents