To read an Excel file in .NET, you can use the EPPlus
library. Here is an example code that reads an Excel file and prints the data from cell A1 and A2:
using OfficeOpenXml; // Load the Excel file using (var package = new ExcelPackage(new FileInfo(@"example.xlsx"))) { // Select the sheet you want to read var sheet = package.Workbook.Worksheets[1]; // Read data from cell A1 var cell_a1 = sheet.Cells["A1"].Value.ToString(); Console.WriteLine(cell_a1); // Read data from cell A2 var cell_a2 = sheet.Cells["A2"].Value.ToString(); Console.WriteLine(cell_a2); }
In this example, we first load the Excel file called “example.xlsx” using the ExcelPackage
class. Then we select the first sheet in the workbook using the Worksheets
property.
We read the data from cell A1 using the Cells
property and the cell reference “A1”. The Value
property returns the value of the cell as an object, which we convert to a string using the ToString()
method.
We do the same thing for cell A2, and finally, we print the values of both cells using the Console.WriteLine()
sheet.Cells
property.