How to Read Excel Files in C# (Developer Tutorial)
This tutorial explains how to read an Excel file in C#, as well as perform everyday tasks like data validation, database conversion, Web API integrations, and formula modification. This article references code examples that utilize the IronXL .NET Excel library.
Steps for Reading Excel Files in C#
- Download the C# Library to read Excel files
- Load and read an Excel file (workbook)
- Create an Excel workbook in CSV or XLSX
- Edit cell values in a range of cells
- Validate spreadsheet data
- Export data using Entity Framework
IronXL facilitates reading and editing Microsoft Excel documents with C#. IronXL neither requires Microsoft Excel nor does it require Interop. In fact, IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel
.
IronXL Includes:
- Dedicated product support from our .NET engineers
- Easy installation via Microsoft Visual Studio
- Free trial test for development. Licenses from $749.
Reading and creating Excel files in C# and VB.NET is easy using the IronXL software library.
Reading .XLS and .XLSX Excel Files Using IronXL
Below is a summary of the overall workflow for reading Excel files using IronXL:
- Install the IronXL Excel Library. You can use the NuGet package or download the .Net Excel DLL.
- Use the
WorkBook.Load
method to read any XLS, XLSX, or CSV document. - Get Cell values using intuitive syntax:
sheet["A11"].DecimalValue
.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;
// Load the workbook from the specified file
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select cell A2 and get its integer value
int cellValue = workSheet["A2"].IntValue;
// Output the value of cell A2
Console.WriteLine("The integer value of cell A2 is: " + cellValue);
// Iterate over the cells in the range A2:A10
foreach (var cell in workSheet["A2:A10"])
{
// Print the address and text value of each cell
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Advanced Operations
// Calculate the sum of the values in the range A2:A10
decimal sum = workSheet["A2:A10"]
.Select(cell => cell.DecimalValue) // Convert each cell value to decimal
.Sum(); // Sum all the decimal values
// Calculate the maximum value in the range A2:A10 using Linq
decimal max = workSheet["A2:A10"]
.Max(c => c.DecimalValue); // Find the maximum decimal value in the range
Console.WriteLine("The sum of the values in the range A2:A10 is: " + sum);
Console.WriteLine("The maximum value in the range A2:A10 is: " + max);
Imports IronXL
Imports System
Imports System.Linq
' Load the workbook from the specified file
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Select cell A2 and get its integer value
Private cellValue As Integer = workSheet("A2").IntValue
' Output the value of cell A2
Console.WriteLine("The integer value of cell A2 is: " & cellValue)
' Iterate over the cells in the range A2:A10
For Each cell In workSheet("A2:A10")
' Print the address and text value of each cell
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
' Advanced Operations
' Calculate the sum of the values in the range A2:A10
Dim sum As Decimal = workSheet("A2:A10").Select(Function(cell) cell.DecimalValue).Sum() ' Sum all the decimal values
' Calculate the maximum value in the range A2:A10 using Linq
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue) ' Find the maximum decimal value in the range
Console.WriteLine("The sum of the values in the range A2:A10 is: " & sum)
Console.WriteLine("The maximum value in the range A2:A10 is: " & max)
The code examples used in the next sections of this tutorial (along with the sample project code) will work on three sample Excel spreadsheets:
Tutorial
1. Download the IronXL C# Library for FREE
Start using IronXL in your project today with a free trial.
The first thing we need to do is install the IronXL.Excel
library, adding Excel functionality to the .NET framework.
Installing IronXL.Excel
is most easily achieved using our NuGet package, although you may also choose to manually install the DLL to your project or to your global assembly cache.
Installing the IronXL NuGet Package
- In Visual Studio, right-click on the project select "Manage NuGet Packages ..."
- Search for the IronXL.Excel package and click on the Install button to add it to the project.
Another way to install the IronXL library is using the NuGet Package Manager Console:
- Open the Package Manager Console.
- Run the following command:
Install-Package IronXL.Excel
Additionally, you can view the package on the NuGet website.
Manual Installation
Alternatively, we can start by downloading the IronXL .NET Excel DLL and manually installing it into Visual Studio.
2. Load an Excel Workbook
The WorkBook
class represents an Excel sheet. To open an Excel file using C#, we use the WorkBook.Load
method, specifying the path of the Excel file.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
// Import necessary libraries
using System;
using IronXL;
// Initially set WorkBook object to null. Loading will be attempted in a try-catch block.
WorkBook workBook = null;
try
{
// Attempt to load the workbook from the specified file path.
// This is a relative path, adjust it according to where the Excel file is located.
workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
// If the workbook is loaded successfully, print a confirmation message.
Console.WriteLine("Workbook loaded successfully.");
// You can now perform further operations on the workbook.
// For example, accessing a specific worksheet:
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");
// Perform operations on the sheet
// Example: print the value of a specific cell (for illustration purposes).
Console.WriteLine("Value of A1: " + sheet["A1"].StringValue);
// Add more operations as needed...
}
catch (Exception ex)
{
// If an error occurs during the loading of the workbook, print out the exception details.
Console.WriteLine("An error occurred while loading the workbook: " + ex.Message);
}
// Important note: Make sure that the IronXL library is properly included in the project.
// This can be done through a NuGet package manager. The IronXL library allows for
// interaction with Excel files (.xlsx, .xls, etc.), facilitating the loading, reading,
// and manipulation of spreadsheet data.
' Import necessary libraries
Imports System
Imports IronXL
' Initially set WorkBook object to null. Loading will be attempted in a try-catch block.
Private workBook As WorkBook = Nothing
Try
' Attempt to load the workbook from the specified file path.
' This is a relative path, adjust it according to where the Excel file is located.
workBook = WorkBook.Load("Spreadsheets\GDP.xlsx")
' If the workbook is loaded successfully, print a confirmation message.
Console.WriteLine("Workbook loaded successfully.")
' You can now perform further operations on the workbook.
' For example, accessing a specific worksheet:
Dim sheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Perform operations on the sheet
' Example: print the value of a specific cell (for illustration purposes).
Console.WriteLine("Value of A1: " & sheet("A1").StringValue)
' Add more operations as needed...
Catch ex As Exception
' If an error occurs during the loading of the workbook, print out the exception details.
Console.WriteLine("An error occurred while loading the workbook: " & ex.Message)
End Try
' Important note: Make sure that the IronXL library is properly included in the project.
' This can be done through a NuGet package manager. The IronXL library allows for
' interaction with Excel files (.xlsx, .xls, etc.), facilitating the loading, reading,
' and manipulation of spreadsheet data.
Each WorkBook
can have multiple WorkSheet
objects. Each represents a single Excel worksheet in the Excel document. Use the WorkBook.GetWorkSheet
method to retrieve a reference to a specific Excel worksheet.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs
// Assume that we are working with a library that deals with workbooks and worksheets.
// This code snippet demonstrates how to find a worksheet by its name within a specific workbook object.
// Ensure that the 'workBook' object is properly instantiated and not null before attempting to retrieve a worksheet.
if (workBook == null)
{
throw new ArgumentNullException(nameof(workBook), "The workbook must be instantiated and cannot be null.");
}
// Use the correct method name and check the return value for handling cases where the worksheet might not be found.
WorkSheet workSheet = workBook.GetWorksheet("GDPByCountry");
// The line above tries to obtain a worksheet named "GDPByCountry" from a workbook object named 'workBook'.
// It assumes the existence of 'workBook', which is an instantiated object with a method 'GetWorksheet'
// that returns a worksheet object by its name.
//
// Potential issues to consider in real-world scenarios:
// 1. Confirm that the 'GetWorksheet' method is correctly spelled with the appropriate case sensitivity.
// This requires checking the documentation or API signature from the library being used.
// 2. Ensure that 'WorkSheet' type is correctly spelled and used; this is also case-sensitive.
// 3. The method may return null or throw an exception if the worksheet is not found.
// Implement error handling to gracefully handle such situations:
//
// Example of error handling:
if (workSheet == null)
{
// Handle the case where the worksheet was not found.
Console.WriteLine("Worksheet 'GDPByCountry' not found in the workbook.");
}
else
{
// Proceed with operations on the found worksheet.
Console.WriteLine("Worksheet 'GDPByCountry' successfully retrieved.");
}
' Assume that we are working with a library that deals with workbooks and worksheets.
' This code snippet demonstrates how to find a worksheet by its name within a specific workbook object.
' Ensure that the 'workBook' object is properly instantiated and not null before attempting to retrieve a worksheet.
If workBook Is Nothing Then
Throw New ArgumentNullException(NameOf(workBook), "The workbook must be instantiated and cannot be null.")
End If
' Use the correct method name and check the return value for handling cases where the worksheet might not be found.
Dim workSheet As WorkSheet = workBook.GetWorksheet("GDPByCountry")
' The line above tries to obtain a worksheet named "GDPByCountry" from a workbook object named 'workBook'.
' It assumes the existence of 'workBook', which is an instantiated object with a method 'GetWorksheet'
' that returns a worksheet object by its name.
'
' Potential issues to consider in real-world scenarios:
' 1. Confirm that the 'GetWorksheet' method is correctly spelled with the appropriate case sensitivity.
' This requires checking the documentation or API signature from the library being used.
' 2. Ensure that 'WorkSheet' type is correctly spelled and used; this is also case-sensitive.
' 3. The method may return null or throw an exception if the worksheet is not found.
' Implement error handling to gracefully handle such situations:
'
' Example of error handling:
If workSheet Is Nothing Then
' Handle the case where the worksheet was not found.
Console.WriteLine("Worksheet 'GDPByCountry' not found in the workbook.")
Else
' Proceed with operations on the found worksheet.
Console.WriteLine("Worksheet 'GDPByCountry' successfully retrieved.")
End If
Creating new Excel Documents
To create a new Excel document, construct a new WorkBook
object with a valid file type.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
using System;
// Namespace declaration for organizing classes related to Excel Workbook examples
namespace ExcelWorkbookExample
{
/// <summary>
/// A simple example demonstrating how to create a workbook in XLSX format.
/// Assumes that a library like EPPlus or a similar one is being used for Excel file handling,
/// since .NET does not natively support Excel file creation without a third-party library.
/// </summary>
public class ExcelWorkbookCreator
{
// Method to create an Excel workbook, though the actual implementation
// of Excel library code is only demonstrated conceptually here.
public void CreateWorkbook()
{
// This method assumes the use of a library, such as EPPlus, to manage Excel files.
// Actual operations such as adding data or saving the file are done through that library's API.
// Placeholder for the Excel library's workbook creation method
// e.g., for EPPlus, you would initialize an ExcelPackage and add a Workbook.
// ExcelPackage package = new ExcelPackage();
// var workBook = package.Workbook;
Console.WriteLine("Workbook created successfully in XLSX format.");
}
}
// Main class and method to demonstrate workbook creation.
// In a real usage scenario, you would probably remove this and call the method from another context.
public static class Program
{
public static void Main()
{
// Instantiation of the ExcelWorkbookCreator class to demonstrate the workbook creation process.
ExcelWorkbookCreator creator = new ExcelWorkbookCreator();
creator.CreateWorkbook();
}
}
}
Imports System
' Namespace declaration for organizing classes related to Excel Workbook examples
Namespace ExcelWorkbookExample
''' <summary>
''' A simple example demonstrating how to create a workbook in XLSX format.
''' Assumes that a library like EPPlus or a similar one is being used for Excel file handling,
''' since .NET does not natively support Excel file creation without a third-party library.
''' </summary>
Public Class ExcelWorkbookCreator
' Method to create an Excel workbook, though the actual implementation
' of Excel library code is only demonstrated conceptually here.
Public Sub CreateWorkbook()
' This method assumes the use of a library, such as EPPlus, to manage Excel files.
' Actual operations such as adding data or saving the file are done through that library's API.
' Placeholder for the Excel library's workbook creation method
' e.g., for EPPlus, you would initialize an ExcelPackage and add a Workbook.
' ExcelPackage package = new ExcelPackage();
' var workBook = package.Workbook;
Console.WriteLine("Workbook created successfully in XLSX format.")
End Sub
End Class
' Main class and method to demonstrate workbook creation.
' In a real usage scenario, you would probably remove this and call the method from another context.
Public Module Program
Public Sub Main()
' Instantiation of the ExcelWorkbookCreator class to demonstrate the workbook creation process.
Dim creator As New ExcelWorkbookCreator()
creator.CreateWorkbook()
End Sub
End Module
End Namespace
Note: Use ExcelFileFormat.XLS
to support legacy versions of Microsoft Excel (95 and earlier).
Add a Worksheet to an Excel Document
As explained previously, an IronXL WorkBook
contains a collection of one or more WorkSheet
s.
To create a new WorkSheet
, call WorkBook.CreateWorkSheet
with the name of the worksheet.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
// This code assumes that a workbook object has been initialized elsewhere in the application.
// It retrieves a worksheet named "GDPByCountry" from the workbook.
// Declare a WorkSheet object to hold the retrieved worksheet named "GDPByCountry."
// 'workBook' must be a valid instance of a class containing the 'GetWorkSheet' method,
// capable of returning a worksheet by its name.
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
// Note:
// - Ensure that 'workBook' is a correctly initialized instance of a class that provides
// the following method:
// public WorkSheet GetWorkSheet(string sheetName)
//
// - Verify that there is indeed a worksheet named "GDPByCountry" within the workbook
// to avoid runtime errors related to null references or similar issues.
' This code assumes that a workbook object has been initialized elsewhere in the application.
' It retrieves a worksheet named "GDPByCountry" from the workbook.
' Declare a WorkSheet object to hold the retrieved worksheet named "GDPByCountry."
' 'workBook' must be a valid instance of a class containing the 'GetWorkSheet' method,
' capable of returning a worksheet by its name.
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
' Note:
' - Ensure that 'workBook' is a correctly initialized instance of a class that provides
' the following method:
' public WorkSheet GetWorkSheet(string sheetName)
'
' - Verify that there is indeed a worksheet named "GDPByCountry" within the workbook
' to avoid runtime errors related to null references or similar issues.
3. Access Cell Values
Read and Edit a Single Cell
Access to the values of individual spreadsheet cells is performed by retrieving the desired cell from its WorkSheet
, as shown below:
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-16.cs
using IronXL;
// Load the existing Excel workbook
WorkBook workBook = WorkBook.Load("test.xlsx");
// Retrieve the default worksheet from the loaded workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Access the cell at B1 location on the worksheet
// The 'First()' method ensures that we are accessing the first cell,
// which is necessary especially when dealing with potential ranges.
IronXL.Cell cell = workSheet["B1"].First();
// At this point, 'cell' contains the cell at position B1 on the default worksheet.
// Further operations can be performed on 'cell', like reading its value or modifying it.
// Example:
// var cellValue = cell.Value; // To read the value of the cell
// cell.Value = "New Value"; // To write a new value into the cell
// Save changes to the workbook if any modifications are made
// workBook.Save();
Imports IronXL
' Load the existing Excel workbook
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
' Retrieve the default worksheet from the loaded workbook
Private workSheet As WorkSheet = workBook.DefaultWorkSheet
' Access the cell at B1 location on the worksheet
' The 'First()' method ensures that we are accessing the first cell,
' which is necessary especially when dealing with potential ranges.
Private cell As IronXL.Cell = workSheet("B1").First()
' At this point, 'cell' contains the cell at position B1 on the default worksheet.
' Further operations can be performed on 'cell', like reading its value or modifying it.
' Example:
' var cellValue = cell.Value; // To read the value of the cell
' cell.Value = "New Value"; // To write a new value into the cell
' Save changes to the workbook if any modifications are made
' workBook.Save();
IronXL's Cell
class represents an individual cell in an Excel spreadsheet. It contains properties and methods that enable users to access and modify the cell's value directly.
With a reference to a Cell
object, you can read and write data to and from a spreadsheet cell.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-17.cs
// Using IronXL library to interact with Excel files is assumed.
// This code demonstrates basic operations like reading from and writing to an Excel worksheet using IronXL.
// IronXL namespace for Excel operations should be used
using IronXL;
// Assuming `workSheet` is a valid Worksheet object initialized elsewhere in the code.
// The `workSheet` object must be properly instantiated before this code is executed.
var workSheet = WorkBook.Load("path/to/excel/file.xlsx").GetWorkSheet("SheetName");
// Retrieve the first cell in the specified range, "B1"
IronXL.Cell cell = workSheet["B1"];
// Read the value of the cell as a string
string value = cell.StringValue;
// Output the current value of the cell to the console
Console.WriteLine("Original Cell Value: " + value);
// Write a new value to the cell
cell.Value = 10.3289;
// Output the updated cell value to the console
Console.WriteLine("Updated Cell Value: " + cell.StringValue);
// Note: Ensure that the IronXL library is correctly referenced in your project
// and that you have the necessary licenses to use the library functions.
' Using IronXL library to interact with Excel files is assumed.
' This code demonstrates basic operations like reading from and writing to an Excel worksheet using IronXL.
' IronXL namespace for Excel operations should be used
Imports IronXL
' Assuming `workSheet` is a valid Worksheet object initialized elsewhere in the code.
' The `workSheet` object must be properly instantiated before this code is executed.
Private workSheet = WorkBook.Load("path/to/excel/file.xlsx").GetWorkSheet("SheetName")
' Retrieve the first cell in the specified range, "B1"
Private cell As IronXL.Cell = workSheet("B1")
' Read the value of the cell as a string
Private value As String = cell.StringValue
' Output the current value of the cell to the console
Console.WriteLine("Original Cell Value: " & value)
' Write a new value to the cell
cell.Value = 10.3289
' Output the updated cell value to the console
Console.WriteLine("Updated Cell Value: " & cell.StringValue)
' Note: Ensure that the IronXL library is correctly referenced in your project
' and that you have the necessary licenses to use the library functions.
Read and Write a Range of Cell Values
The Range
class represents a two-dimensional collection of Cell
objects. This collection refers to a literal range of Excel cells. Obtain ranges by using the string indexer on a WorkSheet
object. For example:
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
// This code snippet assumes that we're working with an Excel worksheet.
// It tries to create a Range object corresponding to the cells D2 through D101 in the worksheet.
// Assuming 'workSheet' is a properly initialized Excel worksheet object in your program
// Here, we create a Range object that represents the range of cells from D2 to D101 in the worksheet.
Range range = workSheet.Range["D2:D101"];
// Explanation of the code:
// - The 'Range' property of the 'workSheet' object is accessed to get the desired cells.
// - 'Range' is a part of the Excel interop library that allows you to define a range of cells.
' This code snippet assumes that we're working with an Excel worksheet.
' It tries to create a Range object corresponding to the cells D2 through D101 in the worksheet.
' Assuming 'workSheet' is a properly initialized Excel worksheet object in your program
' Here, we create a Range object that represents the range of cells from D2 to D101 in the worksheet.
Dim range As Range = workSheet.Range("D2:D101")
' Explanation of the code:
' - The 'Range' property of the 'workSheet' object is accessed to get the desired cells.
' - 'Range' is a part of the Excel interop library that allows you to define a range of cells.
There are several ways to read or edit the values of cells within a Range. If the count is known, use a For loop.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Define the PersonValidationResult class to store validation results for each row
public class PersonValidationResult
{
public int Row { get; set; } // The row number being validated
public string PhoneNumberErrorMessage { get; set; } // Error message for phone number validation
public string EmailErrorMessage { get; set; } // Error message for email validation
public string DateErrorMessage { get; set; } // Error message for date validation
}
// Assuming this code is part of a larger method or context where 'results' and 'worksheet' are defined
// 'results' is a list to store validation results for each row
var results = new List<PersonValidationResult>();
// 'workSheet' is an instance of an EPPlus ExcelWorksheet or similar object that you are working with
var phoneNumberUtil = PhoneNumberUtil.GetInstance(); // Assuming Google libphonenumber is being used for phone validation
// Iterate through the rows of the spreadsheet from row 2 to 101
for (var y = 2; y <= 101; y++)
{
// Initialize a new validation result object for each row
var result = new PersonValidationResult { Row = y };
results.Add(result);
// Get all cells for the person in columns A to E for the current row
// EPPlus may return a range, ensure conversion to a list
var cells = workSheet.Cells[$"A{y}:E{y}"].ToArray();
// Validate the phone number in column B (index 1 in 0-based array)
var phoneNumber = cells[1].Text; // Using Text property in case of number formatting issues
result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, phoneNumber);
// Validate the email address in column D (index 3 in 0-based array)
result.EmailErrorMessage = ValidateEmailAddress(cells[3].Text);
// Get and validate the raw date in column E (index 4 in 0-based array)
var rawDate = cells[4].Text;
result.DateErrorMessage = ValidateDate(rawDate);
}
// Define helper functions
string ValidatePhoneNumber(PhoneNumberUtil phoneNumberUtil, string phoneNumber)
{
// Implement the phone number validation logic here using phoneNumberUtil
// Return an error message if validation fails, else return null or empty string
// Example placeholder logic:
return ""; // placeholder
}
string ValidateEmailAddress(string emailAddress)
{
// Implement the email address validation logic here
// Return an error message if validation fails, else return null or empty string
// Example placeholder logic:
return ""; // placeholder
}
string ValidateDate(string rawDate)
{
// Implement the date validation logic here
// Return an error message if validation fails, else return null or empty string
// Example placeholder logic:
return ""; // placeholder
}
' Define the PersonValidationResult class to store validation results for each row
Public Class PersonValidationResult
Public Property Row() As Integer ' - The row number being validated
Public Property PhoneNumberErrorMessage() As String ' - Error message for phone number validation
Public Property EmailErrorMessage() As String ' - Error message for email validation
Public Property DateErrorMessage() As String ' - Error message for date validation
End Class
' Assuming this code is part of a larger method or context where 'results' and 'worksheet' are defined
' 'results' is a list to store validation results for each row
Private results = New List(Of PersonValidationResult)()
' 'workSheet' is an instance of an EPPlus ExcelWorksheet or similar object that you are working with
Private phoneNumberUtil = PhoneNumberUtil.GetInstance() ' Assuming Google libphonenumber is being used for phone validation
' Iterate through the rows of the spreadsheet from row 2 to 101
For y = 2 To 101
' Initialize a new validation result object for each row
Dim result = New PersonValidationResult With {.Row = y}
results.Add(result)
' Get all cells for the person in columns A to E for the current row
' EPPlus may return a range, ensure conversion to a list
Dim cells = workSheet.Cells($"A{y}:E{y}").ToArray()
' Validate the phone number in column B (index 1 in 0-based array)
Dim phoneNumber = cells(1).Text ' Using Text property in case of number formatting issues
result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, phoneNumber)
' Validate the email address in column D (index 3 in 0-based array)
result.EmailErrorMessage = ValidateEmailAddress(cells(3).Text)
' Get and validate the raw date in column E (index 4 in 0-based array)
Dim rawDate = cells(4).Text
result.DateErrorMessage = ValidateDate(rawDate)
Next y
' Define helper functions
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'string ValidatePhoneNumber(PhoneNumberUtil phoneNumberUtil, string phoneNumber)
'{
' ' Implement the phone number validation logic here using phoneNumberUtil
' ' Return an error message if validation fails, else return null or empty string
' ' Example placeholder logic:
' Return ""; ' placeholder
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'string ValidateEmailAddress(string emailAddress)
'{
' ' Implement the email address validation logic here
' ' Return an error message if validation fails, else return null or empty string
' ' Example placeholder logic:
' Return ""; ' placeholder
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'string ValidateDate(string rawDate)
'{
' ' Implement the date validation logic here
' ' Return an error message if validation fails, else return null or empty string
' ' Example placeholder logic:
' Return ""; ' placeholder
'}
Add Formula to a Spreadsheet
Set the formula of Cell
s with the Formula
property.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-13.cs
// This code block iterates through certain rows in an Excel worksheet and sets a formula for each cell in column C.
// The formula calculates the percentage of the total by dividing the value in column B of the current row
// by the value in column B of the last row. It assumes that 'i' is defined as the boundary row index,
// and 'workSheet' is a previously initialized worksheet object.
for (var y = 2; y < i; y++)
{
// Access the first cell in column C of the current row
Cell cell = workSheet.Cells[$"C{y}"].First(); // Assumes 'Cells' is a valid collection
// Set a formula to the cell that calculates the percentage of the total using the values in column B.
cell.Formula = $"=B{y}/B{i}"; // Formula is calculated as current row value (B{y}) divided by last row value (B{i})
}
' This code block iterates through certain rows in an Excel worksheet and sets a formula for each cell in column C.
' The formula calculates the percentage of the total by dividing the value in column B of the current row
' by the value in column B of the last row. It assumes that 'i' is defined as the boundary row index,
' and 'workSheet' is a previously initialized worksheet object.
Dim y = 2
Do While y < i
' Access the first cell in column C of the current row
Dim cell As Cell = workSheet.Cells($"C{y}").First() ' Assumes 'Cells' is a valid collection
' Set a formula to the cell that calculates the percentage of the total using the values in column B.
cell.Formula = $"=B{y}/B{i}" ' Formula is calculated as current row value (B{y}) divided by last row value (B{i})
y += 1
Loop
This code sets a formula in cell C1 that calculates the sum of cells A1 through A10.
Validate Spreadsheet Data
Use IronXL to validate a sheet of data. The DataValidation
sample might use libraries such as libphonenumber-csharp
to validate phone numbers and standard C# APIs to validate email addresses and dates.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
// This code iterates through rows 2 to 101 of an Excel worksheet, validating data in each row.
// It checks phone numbers, email addresses, and dates, storing any validation error messages found.
for (var i = 2; i <= 101; i++)
{
// Create a new validation result for each row.
// The row number is stored in the result to track which row any errors occur in.
var result = new PersonValidationResult { Row = i };
results.Add(result);
// Get all cells for the individual in the current row using a range from columns A to E.
// The cells are expected to contain relevant data used for validation.
var cells = worksheet[$"A{i}:E{i}"].ToList();
// Validate the phone number located in column B (index 1).
// Conversion of the cell value to a string may be necessary if the value is not naturally a string.
var phoneNumber = cells[1].Value;
result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);
// Validate the email address located in column D (index 3).
// The value can directly be cast to a string as it is expected to be a string type cell.
var emailValue = cells[3].Value as string;
result.EmailErrorMessage = ValidateEmailAddress(emailValue);
// Validate the date located in column E (index 4).
// Dates are retrieved as strings for validation purposes.
var rawDate = cells[4].Value as string;
result.DateErrorMessage = ValidateDate(rawDate);
}
' This code iterates through rows 2 to 101 of an Excel worksheet, validating data in each row.
' It checks phone numbers, email addresses, and dates, storing any validation error messages found.
For i = 2 To 101
' Create a new validation result for each row.
' The row number is stored in the result to track which row any errors occur in.
Dim result = New PersonValidationResult With {.Row = i}
results.Add(result)
' Get all cells for the individual in the current row using a range from columns A to E.
' The cells are expected to contain relevant data used for validation.
Dim cells = worksheet($"A{i}:E{i}").ToList()
' Validate the phone number located in column B (index 1).
' Conversion of the cell value to a string may be necessary if the value is not naturally a string.
Dim phoneNumber = cells(1).Value
result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))
' Validate the email address located in column D (index 3).
' The value can directly be cast to a string as it is expected to be a string type cell.
Dim emailValue = TryCast(cells(3).Value, String)
result.EmailErrorMessage = ValidateEmailAddress(emailValue)
' Validate the date located in column E (index 4).
' Dates are retrieved as strings for validation purposes.
Dim rawDate = TryCast(cells(4).Value, String)
result.DateErrorMessage = ValidateDate(rawDate)
Next i
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
// Ensure the workbook object 'workBook' and the collection of results 'results' are available in the top-level scope
// Create a worksheet named "Results" in the workbook.
var resultsSheet = workBook.CreateWorksheet("Results");
// Set headers for each column in the first row.
resultsSheet["A1"].Value = "Row"; // Column A: Row Number
resultsSheet["B1"].Value = "Valid"; // Column B: Valid Entry Indicator
resultsSheet["C1"].Value = "Phone Error"; // Column C: Phone Number Error Message
resultsSheet["D1"].Value = "Email Error"; // Column D: Email Error Message
resultsSheet["E1"].Value = "Date Error"; // Column E: Date Error Message
// Loop through the list of results to populate the worksheet.
for (var i = 0; i < results.Count; i++)
{
var result = results[i];
// Set the row number in the first column.
resultsSheet[$"A{i + 2}"].Value = i + 1;
// Indicate if the result is valid in the second column.
resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
// Fill in the error messages for phone, email, and date in the respective columns.
resultsSheet[$"C{i + 2}"].Value = string.IsNullOrEmpty(result.PhoneNumberErrorMessage) ? "" : result.PhoneNumberErrorMessage;
resultsSheet[$"D{i + 2}"].Value = string.IsNullOrEmpty(result.EmailErrorMessage) ? "" : result.EmailErrorMessage;
resultsSheet[$"E{i + 2}"].Value = string.IsNullOrEmpty(result.DateErrorMessage) ? "" : result.DateErrorMessage;
}
// Save the workbook to the specified path.
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
' Ensure the workbook object 'workBook' and the collection of results 'results' are available in the top-level scope
' Create a worksheet named "Results" in the workbook.
Dim resultsSheet = workBook.CreateWorksheet("Results")
' Set headers for each column in the first row.
resultsSheet("A1").Value = "Row" ' Column A: Row Number
resultsSheet("B1").Value = "Valid" ' Column B: Valid Entry Indicator
resultsSheet("C1").Value = "Phone Error" ' Column C: Phone Number Error Message
resultsSheet("D1").Value = "Email Error" ' Column D: Email Error Message
resultsSheet("E1").Value = "Date Error" ' Column E: Date Error Message
' Loop through the list of results to populate the worksheet.
For i = 0 To results.Count - 1
Dim result = results(i)
' Set the row number in the first column.
resultsSheet($"A{i + 2}").Value = i + 1
' Indicate if the result is valid in the second column.
resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No")
' Fill in the error messages for phone, email, and date in the respective columns.
resultsSheet($"C{i + 2}").Value = If(String.IsNullOrEmpty(result.PhoneNumberErrorMessage), "", result.PhoneNumberErrorMessage)
resultsSheet($"D{i + 2}").Value = If(String.IsNullOrEmpty(result.EmailErrorMessage), "", result.EmailErrorMessage)
resultsSheet($"E{i + 2}").Value = If(String.IsNullOrEmpty(result.DateErrorMessage), "", result.DateErrorMessage)
Next i
' Save the workbook to the specified path.
workBook.SaveAs("Spreadsheets\PeopleValidated.xlsx")
4. Export Data using Entity Framework
Use IronXL to export data to a database or convert an Excel spreadsheet to a database. The ExcelToDB
sample reads a spreadsheet with GDP by country and then exports that data to an SQLite database utilizing EntityFramework
.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-10.cs
using System;
using System.ComponentModel.DataAnnotations;
// This class represents a Country entity with properties for Key, Name, and GDP.
public class Country
{
// Key attribute is used to annotate the primary key of the entity.
[Key]
public Guid Key { get; set; }
// The name of the country.
public string Name { get; set; }
// The GDP (Gross Domestic Product) value of the country.
public decimal GDP { get; set; }
}
Imports System
Imports System.ComponentModel.DataAnnotations
' This class represents a Country entity with properties for Key, Name, and GDP.
Public Class Country
' Key attribute is used to annotate the primary key of the entity.
<Key>
Public Property Key() As Guid
' The name of the country.
Public Property Name() As String
' The GDP (Gross Domestic Product) value of the country.
Public Property GDP() As Decimal
End Class
To use a different database, install the corresponding NuGet package and find the equivalent of UseSqLite()
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-11.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.Sqlite;
/// <summary>
/// Represents a country entity.
/// </summary>
public class Country
{
/// <summary>
/// Gets or sets the unique identifier for the country.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the name of the country.
/// </summary>
public string Name { get; set; }
}
/// <summary>
/// Represents the database context for accessing the Country database.
/// </summary>
public class CountryContext : DbContext
{
/// <summary>
/// Gets or sets the DbSet of countries.
/// </summary>
public DbSet<Country> Countries { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CountryContext"/> class.
/// Ensures the database is created.
/// </summary>
public CountryContext()
{
// Synchronously ensures that the database for the context is created.
Database.EnsureCreatedAsync().Wait();
}
/// <inheritdoc />
/// <summary>
/// Configures the database context to use SQLite.
/// </summary>
/// <param name="optionsBuilder">The options builder being used for configuration.</param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Establish a connection to an SQLite database.
var connection = new SqliteConnection("Data Source=Country.db");
connection.Open();
// Configure the context to use SQLite with the opened connection.
optionsBuilder.UseSqlite(connection);
// Enforce foreign key constraints in SQLite.
using (var command = connection.CreateCommand())
{
command.CommandText = "PRAGMA foreign_keys = ON;";
command.ExecuteNonQuery();
}
// It is good practice to call the base implementation.
base.OnConfiguring(optionsBuilder);
}
}
Imports System
Imports Microsoft.EntityFrameworkCore
Imports Microsoft.Data.Sqlite
''' <summary>
''' Represents a country entity.
''' </summary>
Public Class Country
''' <summary>
''' Gets or sets the unique identifier for the country.
''' </summary>
Public Property Id() As Integer
''' <summary>
''' Gets or sets the name of the country.
''' </summary>
Public Property Name() As String
End Class
''' <summary>
''' Represents the database context for accessing the Country database.
''' </summary>
Public Class CountryContext
Inherits DbContext
''' <summary>
''' Gets or sets the DbSet of countries.
''' </summary>
Public Property Countries() As DbSet(Of Country)
''' <summary>
''' Initializes a new instance of the <see cref="CountryContext"/> class.
''' Ensures the database is created.
''' </summary>
Public Sub New()
' Synchronously ensures that the database for the context is created.
Database.EnsureCreatedAsync().Wait()
End Sub
''' <inheritdoc />
''' <summary>
''' Configures the database context to use SQLite.
''' </summary>
''' <param name="optionsBuilder">The options builder being used for configuration.</param>
Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
' Establish a connection to an SQLite database.
Dim connection = New SqliteConnection("Data Source=Country.db")
connection.Open()
' Configure the context to use SQLite with the opened connection.
optionsBuilder.UseSqlite(connection)
' Enforce foreign key constraints in SQLite.
Using command = connection.CreateCommand()
command.CommandText = "PRAGMA foreign_keys = ON;"
command.ExecuteNonQuery()
End Using
' It is good practice to call the base implementation.
MyBase.OnConfiguring(optionsBuilder)
End Sub
End Class
Create a CountryContext
, iterate through the range to create each record, and then SaveAsync
to commit data to the database
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-12.cs
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;
// This method processes an Excel worksheet to extract country names and GDP values,
// then saves them into a database.
public async Task ProcessAsync()
{
try
{
// Load the workbook from the specified file path.
var workbook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
// Get the worksheet named "GDPByCountry" from the workbook.
var worksheet = workbook.GetWorkSheet("GDPByCountry");
// Create a database context for interacting with the Country database.
using (var countryContext = new CountryContext())
{
// Iterate through each row of the worksheet from row 2 to 213.
for (var i = 2; i <= 213; i++)
{
// Fetch the range of cells from columns A to B in the current row.
var range = worksheet[$"A{i}:B{i}"].ToList();
// Ensure there are at least two cells in the range.
if (range.Count < 2)
{
continue; // Skip rows that do not have both columns filled.
}
// Create a Country entity object to be stored in the database.
var country = new Country
{
// Extract and cast the value from the first cell as a string for the country's name.
Name = range[0]?.ToString()?.Trim(),
// Extract and cast the value from the second cell as a decimal for the country's GDP.
// Handles potential null by using safe casting and null-coalescing to 0.
GDP = range[1]?.DoubleValue != null ? (decimal)range[1].DoubleValue : 0m
};
// Add the newly created Country entity to the Countries set asynchronously.
await countryContext.Countries.AddAsync(country);
}
// Commit and save all changes made in this context to the database asynchronously.
await countryContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
// Log or handle exceptions here.
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
// Note: Definitions for `Country` entity and `CountryContext` DbContext would also be required
// for this code to be fully functional. Ensure the `CountryContext` class inherits from DbContext
// and that the Entities are properly configured.
Imports System.Threading.Tasks
Imports IronXL
Imports Microsoft.EntityFrameworkCore
' This method processes an Excel worksheet to extract country names and GDP values,
' then saves them into a database.
Public Async Function ProcessAsync() As Task
Try
' Load the workbook from the specified file path.
Dim workbook = WorkBook.Load("Spreadsheets\GDP.xlsx")
' Get the worksheet named "GDPByCountry" from the workbook.
Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
' Create a database context for interacting with the Country database.
Using countryContext As New CountryContext()
' Iterate through each row of the worksheet from row 2 to 213.
For i = 2 To 213
' Fetch the range of cells from columns A to B in the current row.
Dim range = worksheet($"A{i}:B{i}").ToList()
' Ensure there are at least two cells in the range.
If range.Count < 2 Then
Continue For ' Skip rows that do not have both columns filled.
End If
' Create a Country entity object to be stored in the database.
Dim country As New Country With {
.Name = range(0)?.ToString()?.Trim(),
.GDP = If(range(1)?.DoubleValue IsNot Nothing, CDec(range(1).DoubleValue), 0D)
}
' Add the newly created Country entity to the Countries set asynchronously.
Await countryContext.Countries.AddAsync(country)
Next i
' Commit and save all changes made in this context to the database asynchronously.
Await countryContext.SaveChangesAsync()
End Using
Catch ex As Exception
' Log or handle exceptions here.
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Function
' Note: Definitions for `Country` entity and `CountryContext` DbContext would also be required
' for this code to be fully functional. Ensure the `CountryContext` class inherits from DbContext
' and that the Entities are properly configured.
5. Download Data from an API to Spreadsheet
The following call makes a REST call with RestClient.Net. It downloads JSON and converts it into a List
of type RestCountry
. It then iterates through each country and saves the data to an Excel spreadsheet.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-14.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CountryApp
{
// Simulated Client class to demonstrate async HTTP requests.
public class Client
{
private readonly Uri _baseUri;
// Constructor to initialize the client with a base URI.
public Client(Uri baseUri)
{
_baseUri = baseUri;
}
// Asynchronous method to perform a GET request and deserialize the response.
// This is a placeholder for actual HTTP client code.
public async Task<List<RestCountry>> GetAsync()
{
// Note: In a real application, you would replace the following line with HTTP request logic.
// This demonstration assumes a mock response already available as List<RestCountry>.
return await Task.FromResult(new List<RestCountry>
{
// Simulate some response data for demonstration
new RestCountry { Name = "Country1" },
new RestCountry { Name = "Country2" }
});
}
}
// Assume RestCountry is a class with properties matching the expected response data structure.
// This class should be modified to match the expected JSON properties.
public class RestCountry
{
// Example property for demonstration; customize based on actual API response.
public string Name { get; set; }
}
class Program
{
// Main entry point demonstrating usage of the Client class with await functionality.
static async Task Main(string[] args)
{
await RetrieveCountries();
}
// Asynchronous method to initiate HTTP request and process the response.
static async Task RetrieveCountries()
{
// Initialize client with the base URL for the REST API.
var client = new Client(new Uri("https://restcountries.com/v3.1/all"));
// Asynchronously retrieve the list of countries.
List<RestCountry> countries = await client.GetAsync();
// Output the list of countries to demonstrate success.
foreach (var country in countries)
{
Console.WriteLine(country.Name);
}
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Namespace CountryApp
' Simulated Client class to demonstrate async HTTP requests.
Public Class Client
Private ReadOnly _baseUri As Uri
' Constructor to initialize the client with a base URI.
Public Sub New(ByVal baseUri As Uri)
_baseUri = baseUri
End Sub
' Asynchronous method to perform a GET request and deserialize the response.
' This is a placeholder for actual HTTP client code.
Public Async Function GetAsync() As Task(Of List(Of RestCountry))
' Note: In a real application, you would replace the following line with HTTP request logic.
' This demonstration assumes a mock response already available as List<RestCountry>.
Return Await Task.FromResult(New List(Of RestCountry) From {
New RestCountry With {.Name = "Country1"},
New RestCountry With {.Name = "Country2"}
})
End Function
End Class
' Assume RestCountry is a class with properties matching the expected response data structure.
' This class should be modified to match the expected JSON properties.
Public Class RestCountry
' Example property for demonstration; customize based on actual API response.
Public Property Name() As String
End Class
Friend Class Program
' Main entry point demonstrating usage of the Client class with await functionality.
Shared Async Function Main(ByVal args() As String) As Task
Await RetrieveCountries()
End Function
' Asynchronous method to initiate HTTP request and process the response.
Private Shared Async Function RetrieveCountries() As Task
' Initialize client with the base URL for the REST API.
Dim client As New Client(New Uri("https://restcountries.com/v3.1/all"))
' Asynchronously retrieve the list of countries.
Dim countries As List(Of RestCountry) = Await client.GetAsync()
' Output the list of countries to demonstrate success.
For Each country In countries
Console.WriteLine(country.Name)
Next country
End Function
End Class
End Namespace
The original JSON data is given below:
The source code below iterates through the countries and sets the Name, Population, Region, NumericCode, and Top 3 Languages in the spreadsheet.
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-15.cs
// Assumes that the required libraries for working with this type of spreadsheet are imported.
// Assuming existence of a method GetColumnLetter(int index) that returns the corresponding Excel column letter.
// This method is not provided here but should map an integer index to a string representing the Excel column (e.g., 1 -> "A", 2 -> "B").
for (var i = 0; i < countries.Count; i++)
{
var country = countries[i];
// Set the basic values for each country's data in the specified columns.
// i+1 is used to convert zero-based index to Excel row number.
workSheet[$"A{i + 1}"].Value = country.name;
workSheet[$"B{i + 1}"].Value = country.population;
workSheet[$"G{i + 1}"].Value = country.region;
workSheet[$"H{i + 1}"].Value = country.numericCode;
// Iterate through the first 3 languages or the number of available languages, whichever is smaller.
for (var x = 0; x < 3; x++)
{
// Break out of the loop if there are no more languages to process.
if (x >= country.languages.Count) break;
var language = country.languages[x];
// Get the letter representation for the column by computing the correct column shift.
var columnLetter = GetColumnLetter(4 + x); // 4 is used to map to the starting language column ("D")
// Set the language name in the appropriate cell.
workSheet[$"{columnLetter}{i + 1}"].Value = language.name;
}
}
' Assumes that the required libraries for working with this type of spreadsheet are imported.
' Assuming existence of a method GetColumnLetter(int index) that returns the corresponding Excel column letter.
' This method is not provided here but should map an integer index to a string representing the Excel column (e.g., 1 -> "A", 2 -> "B").
For i = 0 To countries.Count - 1
Dim country = countries(i)
' Set the basic values for each country's data in the specified columns.
' i+1 is used to convert zero-based index to Excel row number.
workSheet($"A{i + 1}").Value = country.name
workSheet($"B{i + 1}").Value = country.population
workSheet($"G{i + 1}").Value = country.region
workSheet($"H{i + 1}").Value = country.numericCode
' Iterate through the first 3 languages or the number of available languages, whichever is smaller.
For x = 0 To 2
' Break out of the loop if there are no more languages to process.
If x >= country.languages.Count Then
Exit For
End If
Dim language = country.languages(x)
' Get the letter representation for the column by computing the correct column shift.
Dim columnLetter = GetColumnLetter(4 + x) ' 4 is used to map to the starting language column ("D")
' Set the language name in the appropriate cell.
workSheet($"{columnLetter}{i + 1}").Value = language.name
Next x
Next i
Object Reference and Resources
You may also find the IronXL class documentation within the Object Reference of great value.
In addition, there are other tutorials available for creating, opening, writing, editing, saving, and exporting XLS, XLSX, and CSV files without using Excel Interop.
Summary
IronXL.Excel is a .NET software library for reading a wide variety of spreadsheet formats. It does not require Microsoft Excel to be installed and is not dependent on Interop.
If you find the .NET library useful for modifying Excel files, you might also be interested in exploring the Google Sheets API Client Library for .NET that allows you to modify Google Sheets.
Frequently Asked Questions
What is IronXL?
IronXL is a .NET Excel library that facilitates reading and editing Microsoft Excel documents using C# without requiring Microsoft Excel or Interop.
How do I install the IronXL C# Library?
You can install IronXL using the NuGet package manager in Visual Studio by searching for IronXL.Excel and clicking Install, or by using the NuGet Package Manager Console with the command 'Install-Package IronXL.Excel'.
Can I read both .XLS and .XLSX files using IronXL?
Yes, IronXL supports reading both .XLS and .XLSX Excel file formats using the WorkBook.Load method.
How do I load an Excel workbook in C# using IronXL?
To load an Excel workbook, use the WorkBook.Load method with the path to the Excel file. Then, access a specific worksheet using the GetWorkSheet method.
How can I access and modify cell values in IronXL?
You can access a single cell value using sheet['A1'].Text for reading or setting a value. To modify a range of cells, use the Range class to iterate through cells.
Is it possible to add formulas to an Excel spreadsheet using IronXL?
Yes, you can add formulas to a spreadsheet by setting the Formula property of a Cell object, such as cell.Formula = '=SUM(A1:A10)';
Can IronXL validate spreadsheet data?
IronXL can be used to validate spreadsheet data, such as checking email formats or validating phone numbers, by iterating through cells and applying validation logic.
How do I export data to a database using IronXL?
You can export data to a database by iterating through rows in a worksheet and using an ORM like Entity Framework to save data into a database context.
Is there a way to integrate IronXL with Web APIs?
Yes, IronXL can be integrated with Web APIs to download data and populate Excel spreadsheets, leveraging libraries like RestClient.Net for REST calls.
Does IronXL offer support and licensing options?
IronXL provides dedicated product support from .NET engineers, easy installation, and offers a free trial with licensing options starting from lite licenses.