Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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 ·
Free Resource

Slow SQL Server? These SentryOne resources share tips and tricks for not only troubleshooting SQL Server performance issues, but also preventing them before they hit your production environment.

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.

Database monitoring tools letting you down? See how SentryOne empowers Enterprises to go faster.

Topics:
c# ,excel

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}