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
Let us get started:
: 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.
: 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 ID, Name, 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.
: 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:
<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" />
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.
: Add a
to the Default.aspx
page. We will extract data from the Excel file and bind it to the
: Let us now create a connection to the Excel file and extract data from it. Before that, add a reference to
protected void Page_Load(object sender, EventArgs e)
string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
OleDbConnection oledbConn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
GridView1.DataSource = ds.Tables.DefaultView;
All set!! Run the application and see the data getting displayed in the
. If you want to target the Excel 2007 sheet, just change xls to xlsx in the
I hope this article was useful and I thank you for viewing it.