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

Background

A few days ago I got a requirement to read Excel files and store those values in the Sql server database. So in this example am going to show how to get the basic four import datas 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,

add

add

Namespace

using Excel = Microsoft.Office.Interop.Excel;

C# Code

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

I hope the above information was useful, kindly let me know your thoughts.

 

Leave a Reply

Your email address will not be published. Required fields are marked *