How to read an Excel file using C# MVC 4

Posted on April 19, 2018 by Suresh Kamrushi in

Reading Excel file using C# MVC 4 is very easy. Here I am sharing the code how you can read cell by cell in excel sheets.

1) Right click on Project name on solution explore and then “Add Reference..”
Add Reference

2) On opening of “Reference Manager” popup, look for “Microsoft.Office.Interop.Excel” in “Assemblies” > “Extensions” list and check it. And click “OK” button to enable it.

3) Now to use it in your controller add below namespace:

using Excel = Microsoft.Office.Interop.Excel;

4) Create a method which will read the excel file content and return it. You can refer to below code which expect parameter “fullpath” of excel file on server.

public string excelParsing(string fullpath)
    string data = "";
    //Create COM Objects. Create a COM object for everything that is referenced
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullpath);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

    int rowCount = xlRange.Rows.Count;
    int colCount = xlRange.Columns.Count;

    //iterate over the rows and columns and print to the console as it appears in the file
    //excel is not zero based!!
    for (int i = 1; i <= rowCount; i++)
        for (int j = 1; j <= colCount; j++)
             //either collect data cell by cell or DO you job like insert to DB 
            if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                data += xlRange.Cells[i, j].Value2.ToString();

    return data;

Hope it will help someone to in reading excel file using C# MVC4.

  Comments or questions are welcome  

Tagged as , ,