Read Excel in C# with Simple Code
Source: Dev.to
Introduction
In daily C# development, processing Excel data is a requirement almost every developer encounters. Whether it’s importing user data, generating reports, or conducting data analysis, Excel plays an indispensable role. Traditional C# Excel reading methods—such as Microsoft.Office.Interop.Excel based on COM Interop—are often plagued by performance bottlenecks, environment dependencies, and complex deployment.
This article shows how to implement a simple, efficient Excel reading solution using Spire.XLS for .NET, with no Office dependencies required.
Environment Preparation
Step 1: Create a VS2022 Console Project
- File → New → Project → Console App template.
Step 2: Install via NuGet
-
Graphic Interface: Right‑click the project → Manage NuGet Packages → Search for FreeSpire.XLS.
-
Command Line:
Install-Package Spire.XLS # or the free version Install-Package FreeSpire.XLS
Verify the installation by confirming that the Spire.XLS assembly appears in the project references.
Read Excel Files in C# Quickly
Import the Namespace
using Spire.Xls;
Read Individual Cells
// Load Excel (supports both XLS and XLSX formats)
Workbook wb = new Workbook();
wb.LoadFromFile("Sample.xlsx");
// Read cell data (2 methods)
Worksheet sheet = wb.Worksheets[0];
Console.WriteLine(sheet.Range["A1"].Value); // Locate by column name
Console.WriteLine(sheet.Range[2, 1].Value); // Locate by row and column numbers
Common Pitfall: When reading data by row and column numbers, the indexes start from 1, not 0.
Read Data from an Entire Worksheet
using Spire.Xls;
namespace ReadExcelData
{
class Program
{
static void Main(string[] args)
{
// Load the Excel document
Workbook wb = new Workbook();
wb.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = wb.Worksheets[0];
// Get the data range in the worksheet
CellRange locatedRange = sheet.AllocatedRange;
// Iterate through rows and columns in the range
for (int i = 0; i < locatedRange.Rows.Length; i++)
{
for (int j = 0; j < locatedRange.Rows[i].ColumnCount; j++)
{
// Read cell data
Console.Write(locatedRange[i + 1, j + 1].Value + " ");
}
Console.WriteLine();
}
}
}
}
Read Excel Formulas
The Value property returns the formula itself. To obtain the calculated result, use FormulaValue.
foreach (CellRange cell in sheet.AllocatedRange)
{
if (cell.HasFormula)
{
// Original formula
string formula = cell.Formula;
// Calculated result of the formula
string formulaResult = cell.FormulaValue.ToString();
}
}
Reading Excel files in C# is a common task. Choosing the right tool—such as Spire.XLS—can greatly improve development efficiency and program stability.