Create new account I forgot my password    

Read Data From an Excel File (.xls) in ASP.NET
Rating: 48 user(s) have rated this article Average rating: 4.3
Posted by: Suprotim Agarwal, on 4/8/2008, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 101297 times
Abstract: In this article, we will see how to display data from an Excel spreadsheet using ASP.NET. We will connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then display the data in a GridView.

Read Data From an Excel File (.xlsx) in ASP.NET
 
In this article, we will see how to display data from an Excel spreadsheet using ASP.NET. We will connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then display the data in a GridView. Let us get started.
Step 1: Open Visual Studio > File > New >Website > Under Templates, click ASP.NET WebSite and choose either Visual C# or Visual Basic as the language. Select a location and click Ok.
Step 2: We will create two excel sheets and add them to the project. One excel sheet will be created in Office 2003(.xls) and the other one using Office 2007(.xlsx). Add 4 columns called EID, EName, Age and City to the ‘Sheet1’. Also add some data into the columns. Once these excel files are created, add them to your project. To add them to the project, right click project > Add Existing Item > Add the two excel files.
Step 3: We will now create a web.config file to store the connection string information. Right click project > Add New Item > Web.config. Add the following entries to the file
      <connectionStrings>
            <add name="xls"connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sample1.xls;Extended Properties=Excel 8.0"/>
            <add name="xlsx"connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties=Excel 12.0"/>
      </connectionStrings>
As you can observe, the connection string for xlsx (Excel 2007) contains Microsoft.ACE.OLEDB.12.0 as the provider. This is the new Access database engine OLE DB driver and is also capable of reading Excel 2003.
Step 4: Add a GridView to the Default.aspx page. We will extract  data from the excel file and bind it to the GridView.
Step 5: Let us now create a connection to the excel file and extract data from it. Before that add a reference to System.Data.OleDb;
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
        // Create the connection object
        OleDbConnection oledbConn = new OleDbConnection(connString);
        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;
 
            // Create a DataSet which will hold the data extracted from the worksheet.
            DataSet ds = new DataSet();
 
            // Fill the DataSet from the data extracted from the worksheet.
            oleda.Fill(ds, "Employees");
 
            // Bind the data to the GridView
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch
        {
        }
        finally
        {
            // Close connection
            oledbConn.Close();
        }     
 
    }
VB.NET
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim connString As String = ConfigurationManager.ConnectionStrings("xls").ConnectionString
            ' Create the connection object
            Dim oledbConn As OleDbConnection = New OleDbConnection(connString)
            Try
                  ' Open connection
                  oledbConn.Open()
 
                  ' Create OleDbCommand object and select data from worksheet Sheet1
                  Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn)
 
                  ' Create new OleDbDataAdapter
                  Dim oleda As OleDbDataAdapter = New OleDbDataAdapter()
 
                  oleda.SelectCommand = cmd
 
                  ' Create a DataSet which will hold the data extracted from the worksheet.
                  Dim ds As DataSet = New DataSet()
 
                  ' Fill the DataSet from the data extracted from the worksheet.
                  oleda.Fill(ds, "Employees")
 
                  ' Bind the data to the GridView
                  GridView1.DataSource = ds.Tables(0).DefaultView
                  GridView1.DataBind()
            Catch
            Finally
                  ' Close connection
                  oledbConn.Close()
            End Try
 
      End Sub
All set!! Run the application and see the data getting displayed in the GridView. If you want to target the Excel 2007 sheet, just change xls to xlsx in the ConfigurationManager.ConnectionString.
I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Pratyush Mittal on Tuesday, April 08, 2008 10:41 PM
Can you please tell me what to do if I don't want to hardcore the data files (Sample1.xls - in this case) and take the input from the user ?
Comment posted by Sam on Wednesday, April 09, 2008 5:51 AM
hi, could you please tell me why display error message when run oleda.Fill(ds, "Employees")    exception shown as below
The Microsoft Office Access database engine could not find the object 'Sheet1$'.  Make sure the object exists and that you spell its name and the path name correctly


Thanks for your help!
Comment posted by Suprotim Agarwal on Thursday, April 10, 2008 12:59 AM
Pratyush - You can build the connection string at runtime.
Sam - I will look into the error.

Thanks. Suprotim
Comment posted by f on Saturday, April 19, 2008 6:20 AM
hhhhhhhhh
Comment posted by ff on Saturday, April 19, 2008 6:21 AM
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
Comment posted by Wayne on Monday, April 21, 2008 9:55 AM
Does this solution require Excel to be installed on the system running this .Net app?  I'm getting a similar error as Sam, but I don't have Excel installed.

Also, does this solution require that the spreadsheet store *values* only or can it read *formulas*?
Comment posted by RagaSudha on Wednesday, April 23, 2008 2:12 AM
This is the exception i am getting "The Microsoft Jet database engine could not find the object 'test'.  Make sure the object exists and that you spell its name and the path name correctly"  ,and my excel sheet name is test,where should i specify the path and what is this sample .xls data source for?
Comment posted by hkhk on Wednesday, April 30, 2008 5:48 PM
I had got this error
Error   1   Declaration expected." System.Data.OleDb;"   
Error   2   Type 'OleDbConnection' is not defined.
Error   3   Type 'OleDbCommand' is not defined.   
Error   4   Type 'OleDbDataAdapter' is not defined.   
Error   5   Type 'DataSet' is not defined.   
how could I solve them,,
Thanks alot
Comment posted by hkhk on Thursday, May 01, 2008 9:45 AM
I solved my problem
but there is no result in the browser
what  do you think is the problem?
Comment posted by Suprotim Agarwal on Saturday, May 03, 2008 7:16 AM
Make sure the asp.net user has proper permissions to access & read the file.
Comment posted by NADA on Wednesday, May 07, 2008 2:46 PM
how can I push the dataset into the DB?
Comment posted by dev on Tuesday, May 13, 2008 8:03 PM
hi, i got the following error:

"Could not find installable ISAM. "  
Can someone help please!

Thanks in advance!
Comment posted by dev on Wednesday, May 14, 2008 2:20 PM
hi guys.  I finally got my app work.  I had a similar problem with Sam.  However I noticed that .xls file does not have sheet1, sheet2 or sheet3 at the bottom of the page.  So i assume that's not recognized the object 'Sheet1$' while it's debugging.  In the other hand, a .xlsx file has sheet1, sheet2, and sheet3 at the bottom. So when i run this program and it works.  
Thanks to Suprotim Agarwal!  Keep up the good work.
Comment posted by SM SALMAN on Monday, May 26, 2008 1:44 AM
this all thing working but Data is not Showing In Grid
  oleda.Fill(ds,"Employees"); nothing is Filling on in ds
means ds shows null

Can any one help me how to solve this..?
Comment posted by Pavel on Monday, June 09, 2008 9:39 AM
All problem was in connection string. Example:
if you replace ConfigurationManager.ConnectionStrings["xls"].ConnectionString
on
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
                    & "Data Source=" & Server.MapPath("Sample1.xls") _
                    & ";" & "Extended Properties=Excel 8.0;"
all will be work
MapPath get full path.
If nothing is Filling then make label and add in "Catch ex As Exception" label1.Text = ex.Message ...
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 1:13 PM
dev, Pavel: Thanks for the tip. Strangely, I am able to run the code with the config settings posted. Anyways thanks for sharing your solution for those who were not able to run it.
Comment posted by Marcus on Tuesday, June 24, 2008 5:29 AM
Thanks for your article.  I know you can also write to an excel file using the OLE DB driver.  Do you know how I can write a formula to the Excel file using OLE DB? Thanks.
Comment posted by chin on Thursday, July 10, 2008 9:58 AM
hi!! can you please help me out.. i want to read and populate the data in multiple excel workbooks into a dataset , I know that it can be done using getfiles but not knowing  exactly how to approach? (vb.net)
Comment posted by Mohammad javed on Tuesday, July 15, 2008 1:13 AM
Very Nice code .very very helpful code for every one..
Comment posted by Mohammad Javed on Tuesday, July 15, 2008 1:31 AM
Thanks for your article.  I know you can also write to an excel file using the OLE DB driver.  Do you know how I can write a formula to the Excel file using OLE DB? Thanks.I am able to run the code with the config settings posted. Anyways thanks for sharing your solution for those who
were not able to run it.
Very Nice code .very very helpful code for every one..  
Comment posted by Badal Kant verma on Tuesday, July 15, 2008 1:32 AM
Very Nice code .very very helpful code for every one..
Comment posted by Suprotim Agarwal on Wednesday, July 16, 2008 2:06 PM
Mohammad: I havent really tried writing formulas. However I suggest you to post this question over here for a better response.

http://www.microsoft.com/office/community/en-us/default.mspx?dg=microsoft.public.excel.programming&lang=en&cr=US
Comment posted by arda on Tuesday, July 22, 2008 3:06 AM
how to read excel into datagrid that alrdy has header?Whn i insert textbox into dg column,excel file cant be opend.
Y?Can anyone resolved?
Comment posted by Sat on Thursday, July 24, 2008 12:26 AM
I have a excel sheet, one of the column has decimal values (4.5678764) When i use Microsoft.Jet.OLEDB.4.0;Data Source=file.xls;Extended Properties=Excel 8.0 as connection string and populates my dataset. But dataset only contains value(4.5678) (ie) only 4 digits. Please help me to get all the digits as in excel sheet. Thanks
Comment posted by TechTactics on Friday, March 27, 2009 6:10 AM
Hi Guys,
All who have the Excel Problem...
Lemme just tell you that, whoever is trying to upload an excel sheet with AutoFilter, generally what happens if we autofilter the excel then it creates a dummy sheet on which the filtering happens, so this gets in the way of our ASP.Net code. Please remove the filter and try using. Cheers
Comment posted by Deeraf on Monday, April 13, 2009 3:10 AM
//Edition in the original post.
//EDITION is specified in EDITION region

protected void Page_Load(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
        // Create the connection object
        OleDbConnection oledbConn = new OleDbConnection(connString);
        try
        {
            // Open connection
            oledbConn.Open();
            #region "EDITION"
            DataTable dtSheetName = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dtSheetName == null || dtSheetName.Rows.Count==0)
            {
                if (oledbConn.State == ConnectionState.Open)
                    oledbConn.Close();
                throw new Exception("Unable to find sheet in the selected file.");
            }
            // Create OleDbCommand object and select data from worksheet Sheet1
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM ["+dtSheetName.Rows[0]["TABLE_NAME"].ToString()+"]", oledbConn);
            #endregion
            // Create new OleDbDataAdapter
            OleDbDataAdapter oleda = new OleDbDataAdapter();

            oleda.SelectCommand = cmd;

            // Create a DataSet which will hold the data extracted from the worksheet.
            DataSet ds = new DataSet();

            // Fill the DataSet from the data extracted from the worksheet.
            oleda.Fill(ds, "Employees");

            // Bind the data to the GridView
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch
        {
        }
        finally
        {
            // Close connection
            oledbConn.Close();
        }      

    }
Comment posted by Jessica on Thursday, April 16, 2009 9:09 AM
Unfortunately it doesn't work. Nothing displayed on webpage!!!
Comment posted by akshay on Thursday, April 16, 2009 3:17 PM
I was alos getting the same error as SAM. I copied the dll to debug and release folder then it started working.

I am not sure the reason. but definately with code access security..

Thanks
akshay
Comment posted by Suprotim Agarwal on Friday, April 17, 2009 5:54 AM
Thanks Akshay.

@Everyone - This sample works well in most cases. For special cases, where you have AutoFilter or code issues, read TechTactics, Dheeraf or Akshay's tip. Thanks for your tips!
Comment posted by Alan on Friday, April 24, 2009 7:11 AM
This is a nice solution to my problem, although I have one issue.  One column in my Excel spreadsheet is populated by, predominantly, a number, but in very few cases it could be a string.  When running the code listed here the string value is read into the dataset as type DBNull while all the numbers are of type Double.  Is there any way of ensuring that all data in this column is read as a string?
Comment posted by A Different Alan on Thursday, April 30, 2009 10:10 PM
@Alan: Ah, yes, the pernicious type setting in Excel. By default, the Jet driver only samples the first 8 lines of the file to determine the type. So, alter the registry item HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\Excel and
change "TypeGuessRows" to 0. This will cause it look at all rows before setting the type.

Also, just want to point out that Jet is considered deprecated and is not available in native 64-bit mode.
Comment posted by Chris on Thursday, June 04, 2009 4:03 PM
I'm getting Sam's error. I assumed the sample would run and copied code into an existing application. I have a file named "Wintel_May09_VIAR.xslt". I set the connection string on the fly (I have an upload process that precedes the attempt to open the file). My "sheet" has the same name as the file minus the .xslt. The spread sheet has a number of columns, one of which is named "Address". The error is: The Microsoft Office Access database engine could not find the object 'Address'. Looking at the package contents, my tables folder contains a collection of tables. table1 has a tableColumn with a uniqueName of "Address". What do I need to change?
Comment posted by oaksong on Thursday, June 04, 2009 4:21 PM
Someone should point out that the '$' tacked onto the name of the sheet name is required. I added the '$' and everything worked.
Comment posted by Westham on Saturday, June 06, 2009 6:59 AM
Use this:
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filename + @"; Extended Properties=""Excel 8.0;IMEX=1;HDR=YES""";

then it will work

www.helheten.net
Comment posted by khalil on Sunday, June 07, 2009 3:50 AM
It working now after i created Connection String in code ,not reading it from Web.Config

string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath("Excel2007.xlsx") + ";" + "Extended Properties=Excel 12.0;";

thanks
Comment posted by Wahab Hussain on Tuesday, June 09, 2009 2:08 AM
You guys can check this article as well. Here you can read the data from excel as well as write the data to excel.
http://www.codeproject.com/KB/vb/ExcelDataManipulation.aspx
Comment posted by Suprotim Agarwal on Wednesday, June 10, 2009 3:56 AM
Thanks oaksong, Westham, Khalil for pointing out solutions to those whose code was not working.

Wahab: Thanks for that link
Comment posted by filip on Tuesday, July 14, 2009 7:30 AM
Hi,

nice article but oledb connection is slow way to work with Excel files. You could try using some 3rd party component like GemBox.Spreadsheet - .NET component for Excel which is free for commercial use (limit is 150 rows).

http://www.gemboxsoftware.com/GBSpreadsheet.htm

Filip
Comment posted by mrk on Friday, September 25, 2009 9:13 AM
I am trying to read from Excel 2003 sheet. I am getting the following error when I try to open the connection:
"The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data."

The connection string I am uisng is "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=YES;';Data Source =CI.xls".

No idea where I am going wrong.

Thanks in advance,
mrk
Comment posted by Ajk on Wednesday, October 21, 2009 11:48 AM
This code works perfect as it suppose to. and Thank you for the code. i made the following change though.. to make it read more excel files..

1)
web.config added {0}

   <add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0"/>

2)
in the VS project/solution did create create a folder called excel and put all .xls files under to use the following code

string connString = string.Format(ConfigurationManager.ConnectionStrings["xls"].ConnectionString, Server.MapPath(@"\excel\mysample.xls")) ;
            // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
            try
            {
                // Open connection
                oledbConn.Open();
                string sql = "SELECT * FROM [Sheet1$]";
   
.............
...................



again thanks..
Comment posted by ANSHUMAN on Tuesday, October 27, 2009 7:20 AM
Hi All,

I have generated an xml spreadsheet (*.xls) using XSL. I have another program that reads this spreasheet and processes it.

Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filnavn + ";" + "Extended Properties=Excel 8.0;"

        Dim objCon As OleDbConnection = New OleDbConnection(sConnectionString)

        objCon.Open()  // Here i get the EXCEPTION - External table is not in Expected format

        Dim objCmdSelect As OleDbCommand = New OleDbCommand("SELECT * FROM [General$]", objCon)

        Dim objAdapater As OleDbDataAdapter = New OleDbDataAdapter()

        objAdapater.SelectCommand = objCmdSelect

        Dim _DSGen As DataSet = New DataSet()

        objAdapater.Fill(_DSGen)

I m facing an issue while opening a connection to the generated spreadsheet. It says "{"External table is not in the expected format."}".

My Connection string is

Dim "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filnavn + ";" + "Extended Properties=Excel 8.0;"

Do i need to change anything to this string ? I tried using a dataset and calling dataSet.ReadXml(excelFileName); But the dataset doesnt contain my table. Any inputs on how to read an xml spreadsheet ?

1.How to read XML SpreadSheet in OleDb? How to Convert XML SpreadSheet to Microsoft Office Excel Sheet?

2.How to import "XML Spreadsheet" data into DataTable? Any Other Methods available?

Many Thanks
Comment posted by Thureni on Wednesday, December 02, 2009 1:44 AM
Hi, is it possible to read the first sheet regardless of the sheet's name?
Comment posted by Emanuele on Saturday, December 05, 2009 3:09 AM
I'm a rookie in asp.net and i'm trying to understand your code but using my own file excel i don't receive any data...
i tryied to add a Label and to fill a text "complete" after the GridView1.DataBind(), but i don't receive any answer...

I'm looking for the download code to see if i make any mistakes, but i don't find anything...

could you please help me???

Thanks
Emanuele
Comment posted by Madan Chauhan on Thursday, January 21, 2010 2:40 AM
Hi to all
basically the problem is on path of excel file my code is working fine
  string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("Authors.xls") + ";" + "Extended Properties=Excel 8.0;";

        OleDbConnection oledbconn = new OleDbConnection(connString);
        try
        {
            oledbconn.Open();
            OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", oledbconn);
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            oleda.Fill(ds, "Authors");
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch (OleDbException ex)
        {
            lblMessage.Text = ex.Message;
        }
        finally
        {
            oledbconn.Close();
        }
Comment posted by Ayyappadas on Friday, February 05, 2010 6:12 AM
how use where condition.plz help
Comment posted by Ron on Friday, February 19, 2010 4:26 AM
Yup This Works. Make sure the Path is right.

Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
                    & "Data Source=" & Server.MapPath("Sample1.xls") _
                    & ";" & "Extended Properties=Excel 8.0;"
Comment posted by Ramesh on Wednesday, April 14, 2010 8:53 AM
How to compare two excel sheets and insert the records in sql by c#coding(Asp.net)
Comment posted by Xenam on Wednesday, April 28, 2010 3:12 PM
Well, this method works perfect.. but i want to know if it is possible to use the data in the excel file to be stored in a Oracle Table(not SqlServer) having same field names as that of the excel file..
Comment posted by as on Tuesday, June 29, 2010 4:42 AM
asd
Comment posted by akhter hussain on Tuesday, June 29, 2010 8:10 AM
very good and easy to understand...thanks allot..doodho nahao pooto bhalo beta.......
Comment posted by akhter hussain on Wednesday, June 30, 2010 1:28 AM
very good and easy to understand...thanks allot..doodho nahao pooto bhalo beta.......
Comment posted by Peter on Wednesday, July 07, 2010 11:37 PM
Great article ! I use a best tool for creating an Excel Spreadsheet with C#,  it can reading and writing to excel 97 ~ 2010 from c#,extremely easy to use,I use it long time quit good.
http://www.e-iceblue.com/Introduce/excel-for-net-introduce.html

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER