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,
Namespace
using Excel = Microsoft.Office.Interop.Excel;
Source Code
C# Code
- protected void BtnGetExcelFileDetails_Click(object sender, EventArgs e)
- {
- try
- {
- //create a instance for the Excel object
- Excel.Application oExcel = new Excel.Application();
- //specify the file name where its actually exist
- string filepath = @ "D:\TPMS\Uploaded_Boq\Raveena_boq_From_Db.xlsx";
- //pass that to workbook object
- Excel.Workbook WB = oExcel.Workbooks.Open(filepath);
- // statement get the workbookname
- string ExcelWorkbookname = WB.Name;
- // statement get the worksheet count
- int worksheetcount = WB.Worksheets.Count;
- Excel.Worksheet wks = (Excel.Worksheet) WB.Worksheets[1];
- // statement get the firstworksheetname
- string firstworksheetname = wks.Name;
- //statement get the first cell value
- var firstcellvalue = ((Excel.Range) wks.Cells[1, 1]).Value;
- } catch (Exception ex)
- {
- string error = ex.Message;
- }
- }
Hope the above information was useful.