20

Could someone point me in the right direction on how to read a Excel spreasheet, loop through all the rows and columns to retreive value using EPPlus and MVC? So fare I see examples to create a spreasheet, but did not find any on opening an excel file and read values from it. Any help would be appreciated.

TIA Sue..

sansid
  • 575
  • 3
  • 10
  • 20

2 Answers2

23

Simple example

// Get the file we are going to process
var existingFile = new FileInfo(filePath);
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile))
{
    // Get the work book in the file
    var workBook = package.Workbook;
    if (workBook != null)
    {
        if (workBook.Worksheets.Count > 0)
        {
            // Get the first worksheet
            var currentWorksheet = workBook.Worksheets.First();

            // read some data
            object col1Header = currentWorksheet.Cells[1, 1].Value;
Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
weismat
  • 7,195
  • 3
  • 43
  • 58
  • awesome..thanks..i can take it off to my requirements from here. – sansid Jul 30 '12 at 08:55
  • 9
    Notice that index for rows and columns start at 1, so "Cells[0, 1]" should be "Cells[1, 1]" – amcdrmtt Nov 22 '12 at 10:06
  • 3
    For developers new to this topic, you will need "using" statements for System; System.IO; and OfficeOpenXml; to run this sample. – David Jul 25 '16 at 17:02
5

A simple example how you can read excel file using EPPlus in .net 4.5

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
            }
        }
    }
}
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90