A Guide to Reading and Writing Excel Files in C#
Reading and creating Excel (XLS, XLSX, and CSV) files in C# and other .NET languages is easy using the IronXL software library from Iron Software.
IronXL does not require Excel Interop to be installed on your server. IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel.
IronXL works on the following platforms:
- .NET Framework 4.6.2 and above for Windows and Azure
- .NET Core 2 and above for Windows, Linux, MacOS, and Azure
- .NET 5, .NET 6, .NET 7, .NET 8, Mono, Maui, and Xamarin
Install IronXL
Firstly install IronXL, using our NuGet package or by downloading the DLL. IronXL classes can be found in the IronXL
namespace.
The easiest way to install IronXL is using the NuGet Package Manager for Visual-Studio: The package name is IronXL.Excel.
Install-Package IronXL.Excel
https://www.nuget.org/packages/ironxl.excel/
Reading an Excel Document
With IronXL, extracting data from an Excel file can be done in just a few lines of code.
:path=/static-assets/excel/content-code-examples/get-started/get-started-1.cs
using System;
using System.Linq;
using IronXL;
// The code below demonstrates how to read a spreadsheet using the IronXL library.
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV.
// Load the workbook from the specified file
WorkBook workBook = WorkBook.Load("data.xlsx");
// Get the first worksheet from the workbook
WorkSheet workSheet = workBook.WorkSheets.First();
// Select a specific cell in Excel notation and get its integer value
int cellValue = workSheet["A2"].IntValue;
Console.WriteLine("The value of cell A2 is: {0}", cellValue);
// Iterate over a range of cells in the specified range (A2:B10)
// Print the address and text value of each cell
foreach (var cell in workSheet["A2:B10"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
Imports System
Imports System.Linq
Imports IronXL
' The code below demonstrates how to read a spreadsheet using the IronXL library.
' Supported spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV.
' Load the workbook from the specified file
Private workBook As WorkBook = WorkBook.Load("data.xlsx")
' Get the first worksheet from the workbook
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Select a specific cell in Excel notation and get its integer value
Private cellValue As Integer = workSheet("A2").IntValue
Console.WriteLine("The value of cell A2 is: {0}", cellValue)
' Iterate over a range of cells in the specified range (A2:B10)
' Print the address and text value of each cell
For Each cell In workSheet("A2:B10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
Creating New Excel Documents
IronXL offers a quick and easy interface for generating Excel documents using C# or VB.NET.
:path=/static-assets/excel/content-code-examples/get-started/get-started-2.cs
using IronXL;
// Create a new Excel WorkBook document in XLSX format.
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Set the author metadata for the WorkBook.
workBook.Metadata.Author = "IronXL";
// Add a new blank WorkSheet to the WorkBook.
WorkSheet workSheet = workBook.CreateWorkSheet("main_sheet");
// Set the value of cell A1 to "Hello World".
workSheet["A1"].Value = "Hello World";
// Apply styling to cell A2: set the bottom border color and type.
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600"); // Set border color to orange.
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double; // Set border to double line.
// Save the workbook to a file named "NewExcelFile.xlsx".
workBook.SaveAs("NewExcelFile.xlsx");
Imports IronXL
' Create a new Excel WorkBook document in XLSX format.
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Set the author metadata for the WorkBook.
workBook.Metadata.Author = "IronXL"
' Add a new blank WorkSheet to the WorkBook.
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("main_sheet")
' Set the value of cell A1 to "Hello World".
workSheet("A1").Value = "Hello World"
' Apply styling to cell A2: set the bottom border color and type.
workSheet("A2").Style.BottomBorder.SetColor("#ff6600") ' Set border color to orange.
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double ' Set border to double line.
' Save the workbook to a file named "NewExcelFile.xlsx".
workBook.SaveAs("NewExcelFile.xlsx")
Exporting as CSV, XLS, XLSX, JSON or XML
IronXL also allows you to save or export data to a variety of popular structured spreadsheet formats.
:path=/static-assets/excel/content-code-examples/get-started/get-started-3.cs
// The following code demonstrates how to save a worksheet in various file formats using a fictional or third-party API.
//
// This assumes you have a 'workSheet' object instantiated from a library that supports saving in multiple formats.
// Please ensure your actual usage complies with the API you're using.
// Save the worksheet as an Excel 97-2003 Workbook (.xls)
workSheet.SaveAs("NewExcelFile.xls");
// Save the worksheet as an Excel Workbook (.xlsx)
workSheet.SaveAs("NewExcelFile.xlsx");
// Save the worksheet as a CSV (Comma-Separated Values) file
workSheet.SaveAsCsv("NewExcelFile.csv");
// Save the worksheet as a JSON file
workSheet.SaveAsJson("NewExcelFile.json");
// Save the worksheet as an XML file
workSheet.SaveAsXml("NewExcelFile.xml");
// Note: The above method calls assume that each method (SaveAs, SaveAsCsv, SaveAsJson, SaveAsXml) is defined and properly implemented
// to handle the saving process of the worksheet and that they accept a file path or name as a parameter.
' The following code demonstrates how to save a worksheet in various file formats using a fictional or third-party API.
'
' This assumes you have a 'workSheet' object instantiated from a library that supports saving in multiple formats.
' Please ensure your actual usage complies with the API you're using.
' Save the worksheet as an Excel 97-2003 Workbook (.xls)
workSheet.SaveAs("NewExcelFile.xls")
' Save the worksheet as an Excel Workbook (.xlsx)
workSheet.SaveAs("NewExcelFile.xlsx")
' Save the worksheet as a CSV (Comma-Separated Values) file
workSheet.SaveAsCsv("NewExcelFile.csv")
' Save the worksheet as a JSON file
workSheet.SaveAsJson("NewExcelFile.json")
' Save the worksheet as an XML file
workSheet.SaveAsXml("NewExcelFile.xml")
' Note: The above method calls assume that each method (SaveAs, SaveAsCsv, SaveAsJson, SaveAsXml) is defined and properly implemented
' to handle the saving process of the worksheet and that they accept a file path or name as a parameter.
Styling Cells and Ranges
You can apply formatting to Excel cells and ranges using the IronXL.Range.Style object.
:path=/static-assets/excel/content-code-examples/get-started/get-started-4.cs
// Assuming 'workSheet' is an instance of 'IronXL.WorkSheet',
// this code snippet demonstrates how to set a cell's value and style in IronXL.
// Assign the value "Hello World" to cell A1
workSheet["A1"].Value = "Hello World";
// Set the bottom border color of cell A2 to a hex color code
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
// Set the bottom border type of cell A2 to 'Double' for a thicker, double-line style
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
// Note: Ensure that the IronXL library is properly referenced in your project
// and 'workSheet' is a valid IronXL.WorkSheet instance. The IronXL library
// allows for enhanced manipulation of Excel files, with additional features
// such as modifying styles and formatting, beyond basic data entry.
' Assuming 'workSheet' is an instance of 'IronXL.WorkSheet',
' this code snippet demonstrates how to set a cell's value and style in IronXL.
' Assign the value "Hello World" to cell A1
workSheet("A1").Value = "Hello World"
' Set the bottom border color of cell A2 to a hex color code
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
' Set the bottom border type of cell A2 to 'Double' for a thicker, double-line style
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double
' Note: Ensure that the IronXL library is properly referenced in your project
' and 'workSheet' is a valid IronXL.WorkSheet instance. The IronXL library
' allows for enhanced manipulation of Excel files, with additional features
' such as modifying styles and formatting, beyond basic data entry.
Sorting Ranges
With IronXL, you can sort a range of Excel cells easily using the Range object.
:path=/static-assets/excel/content-code-examples/get-started/get-started-5.cs
// Import the IronXL library, which provides functionalities to work with Excel files
using IronXL;
using System.Linq; // Required for using LINQ methods like First()
// Load the workbook from the specified Excel file
WorkBook workBook = WorkBook.Load("test.xls");
// Access the first worksheet in the workbook
WorkSheet workSheet = workBook.WorkSheets.First();
// Define a range in the worksheet. This range selects the cells from A2 to A8.
Range range = workSheet["A2:A8"];
// Sort the range in ascending order. The cells in the range will be sorted based on their values.
range.SortAscending();
// Save the changes made to the workbook back to the file
workBook.Save();
' Import the IronXL library, which provides functionalities to work with Excel files
Imports IronXL
Imports System.Linq ' Required for using LINQ methods like First()
' Load the workbook from the specified Excel file
Private workBook As WorkBook = WorkBook.Load("test.xls")
' Access the first worksheet in the workbook
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Define a range in the worksheet. This range selects the cells from A2 to A8.
Private range As Range = workSheet("A2:A8")
' Sort the range in ascending order. The cells in the range will be sorted based on their values.
range.SortAscending()
' Save the changes made to the workbook back to the file
workBook.Save()
Editing Formulas
Modifying an Excel formula is as simple as assigning a value that begins with an "=" sign. The formula will be calculated instantly.
:path=/static-assets/excel/content-code-examples/get-started/get-started-6.cs
// This code snippet demonstrates how to set a formula in an Excel worksheet and then retrieve the calculated value.
// It assumes that "workSheet" is an object of a class designed for interaction with Excel worksheets.
// The following line sets a formula in cell A1 to calculate the sum of cells A2 to A10.
workSheet["A1"].Formula = "=SUM(A2:A10)";
// The following line retrieves the calculated decimal value of the formula in cell A1.
// The 'DecimalValue' property is used here to obtain the calculated result of the formula.
decimal sum = workSheet["A1"].DecimalValue;
// Note: The actual object type of workSheet and the referencing mechanism (e.g., workSheet["A1"])
// depend on the library being used for Excel spreadsheet manipulation. The object 'workSheet' should
// be of a compatible type from your chosen library. Make sure to refer to that library's documentation
// to ensure correct usage and syntax.
' This code snippet demonstrates how to set a formula in an Excel worksheet and then retrieve the calculated value.
' It assumes that "workSheet" is an object of a class designed for interaction with Excel worksheets.
' The following line sets a formula in cell A1 to calculate the sum of cells A2 to A10.
workSheet("A1").Formula = "=SUM(A2:A10)"
' The following line retrieves the calculated decimal value of the formula in cell A1.
' The 'DecimalValue' property is used here to obtain the calculated result of the formula.
Dim sum As Decimal = workSheet("A1").DecimalValue
' Note: The actual object type of workSheet and the referencing mechanism (e.g., workSheet["A1"])
' depend on the library being used for Excel spreadsheet manipulation. The object 'workSheet' should
' be of a compatible type from your chosen library. Make sure to refer to that library's documentation
' to ensure correct usage and syntax.
Why Choose IronXL?
IronXL offers a developer-friendly API for reading and writing Excel documents in .NET. It works without requiring Microsoft Excel or Excel Interop to be installed on the server, making Excel file handling fast, lightweight, and hassle-free.
Moving Forward
To explore more features and capabilities, we recommend reviewing the .NET API Reference formatted similarly to MSDN documentation.