【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. However, traditional C# Excel reading methods—such as Microsoft.Office.Interop.Excel based on COM Interop—are often plagued by pain points like performance bottlenecks, environment dependencies, and complex deployment.
This article introduces how to implement a simple, efficient Excel reading solution using Spire.XLS for .NET, with no Office dependencies required.
I. 🔧 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 install the free version:
install-package FreeSpire.XLS
Verify successful installation: Check that the Spire.XLS assembly appears in the project references.
II. ▶️ Read Excel Files in C# Quickly
Import the namespace:
using Spire.Xls;
Read data:
// 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: Indexing
When reading data by row and column numbers, the indexes start from 1.
Read Data from an Entire Excel Worksheet
Read all data via loops:
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();
}
}
}
}
III. 🧩 Read Excel Formulas
The Value property returns the formula directly. To read the calculated result of the formula:
foreach (CellRange cell in sheet.AllocatedRange)
{
if (cell.HasFormula)
{
// Get the original formula
string formula = cell.Formula;
// Get the calculated result of the formula (use FormulaValue directly)
string formulaResult = cell.FormulaValue.ToString();
}
}
Reading Excel in C# is a common task in development. Choosing the right tool can greatly improve development efficiency and program stability.
Top comments (0)