Share via


Read Excel Files Using Microsoft Office Interop Assemblies in ASP.NET C#


Background

A few days ago we got a requirement to read Excel files and store those values in the SQL server database. So in this example, we're going to show how to get the basic four import data such as Excel Work Book Name, Worksheet Count in that Workbook, Name of the First Worksheet, and finally the value of the first cell in that worksheet.

Prerequisites

Kindly ensure you add the following DLL as shown in the below screenshot,

http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/06112016043745AM/image001.jpg

http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/06112016043745AM/image002.jpg

Namespace

using Excel = Microsoft.Office.Interop.Excel;

Source Code

C# Code

  1. protected void BtnGetExcelFileDetails_Click(object sender, EventArgs e)   
  2. {  
  3.   
  4.     try   
  5.     {  
  6.         //create a instance for the Excel object  
  7.         Excel.Application oExcel = new Excel.Application();  
  8.   
  9.         //specify the file name where its actually exist  
  10.         string filepath = @ "D:\TPMS\Uploaded_Boq\Raveena_boq_From_Db.xlsx";  
  11.   
  12.         //pass that to workbook object  
  13.         Excel.Workbook WB = oExcel.Workbooks.Open(filepath);  
  14.   
  15.   
  16.         // statement get the workbookname  
  17.         string ExcelWorkbookname = WB.Name;  
  18.   
  19.         // statement get the worksheet count  
  20.         int worksheetcount = WB.Worksheets.Count;  
  21.   
  22.         Excel.Worksheet wks = (Excel.Worksheet) WB.Worksheets[1];  
  23.   
  24.         // statement get the firstworksheetname  
  25.   
  26.         string firstworksheetname = wks.Name;  
  27.   
  28.         //statement get the first cell value  
  29.         var firstcellvalue = ((Excel.Range) wks.Cells[1, 1]).Value;  
  30.   
  31.     } catch (Exception ex)   
  32.     {  
  33.   
  34.         string error = ex.Message;  
  35.     }  
  36.   
  37. }  

Hope the above information was useful.