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

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

by Karthik Sachin   on Jul 21, 2016   Category: ASP.NET  | Level: Beginner  |  Views: 238    |  Points: 100   
Like this article? Bookmark and Share:
In this article you will learn how to 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.   
  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. }  
I hope the above information was useful, kindly let me know your thoughts.



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts