Over a million developers have joined DZone.

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

Read through the quick tutorial to learn how to read Excel files and store them in SQL Server with Office Interop Assemblies and a bit of C#.

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.

Background

A few days ago, I was required to read Excel files and store those values in our SQL Server database. So, in this example am going to show how to get four basic import data types: 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 below.


add


add


Namespace

using Excel = Microsoft.Office.Interop.Excel;

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;  
    }  

}  


I hope the above information was useful! Please let me know your thoughts.

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:
c# ,excel

Published at DZone with permission of Karthik Elumalai. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}