Home > ASP.NET > Read Excel file from ASP.NET C#

Read Excel file from ASP.NET C#

Really excited to get a snippet that reads the excel file as database table:)

Sample code below

        string connStrExcel = "";
        if (type.Equals("xlsx"))
        {
          connStrExcel = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourExcelFilePath.xlsx;Extended Properties=Excel 12.0";
        }
        else
        {
          connStrExcel = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourExcelFilePath.xls;Extended Properties=Excel 8.0";
        }
        OleDbConnection oledbConn = new OleDbConnection(connStrExcel);
        DataTable tab = new DataTable();

        try
        {   //Open connection
            oledbConn.Open();
           // Create OleDbCommand object and select data from worksheet Sheet1
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
           // Create new OleDbDataAdapter
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
            // Fill the DataTable from the data extracted from the worksheet.
            oleda.Fill(tab);
        }
        finally             '
        {
           oledbConn.Close();
        }

Happy Coding:)

Advertisements
Categories: ASP.NET Tags:
  1. jessie
    March 5, 2014 at 8:14 am

    I have also found code in C#/.NET that reads data from excel and show it in DataTable form and from there you can store the data directly to the datatbase. But you are going to need Aspose.Cells for .NET Library for this and this library has a documentation page where you can find many code samples for other excel features also.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: