Tips n Tracks

  • Increase font size
  • Default font size
  • Decrease font size
  • default color
  • black color

Reference

Sample image

Microsoft .NET Framework Get Details.

Sample image

Microsoft .NET Framework Get Details.

Reference

Sample image Microsoft .NET Framework Get Details.
Sample image

Microsoft .NET Framework Get Details.


Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET


Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET

Microsoft Office Excel is a spreadsheet-application which a good mean to store data in spreadsheet in a table (tabular) form. In this article, we will see how to display data (retrive data or read data) from an Excel spreadsheet using ASP.NET.

We are reading an Excel file in ASP.NET. Our ASP page will be on remote server and an Excel file in our desktop. First of all we need to upload it to a remote server and then retrive the data. So we are design a form to upload an excel. There will be possibility that we have to retrive data from a file again and again so we will rename Excel and then upload it.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title>
<style type="text/css">
tr.sectiontableentry1 td,
tr.sectiontableentry2 td {
padding: 4px;
}
tr.sectiontableentry1 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom;
}
tr.sectiontableentry2 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom #F2F2F2;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="padding: 5px; font-size: 11px;" align="center" border="0">
<tbody>
<tr>
<td>
<strong>Please Select Excel file containing job details…</strong>
</td>
</tr>
<tr>
<td>
<div style="background: url(hline.gif) repeat-x bottom #F2F2F2;padding: 8px 5px;border-bottom: 1px solid #ccc;">
<asp:FileUpload ID="txtFilePath" runat="server"></asp:FileUpload>&nbsp;&nbsp;
<asp:Button ID="btnUpload" runat="server" Text="Upload" /><br />
<asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True"
ForeColor="#009933"></asp:Label>
</div>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grvExcelData" runat="server">
<RowStyle CssClass="sectiontableentry2" />
<AlternatingRowStyle CssClass="sectiontableentry1" />
</asp:GridView>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>

Connection to Excel with Microsoft OLE DB Provider for Jet

The Microsoft OLE DB Provider for Jet(stands for Joint Engine Technology is a database engine) provides an OLE DB interface to Microsoft Access databases, and allows SQL Server 2005 and later distributed queries to query Access databases and Excel spreadsheets. We will connect to a Microsoft Excel workbook using the Microsoft OLE DB Provider for Jet 4.0, read data and then display the data in a GridView.

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. We are going to use it to read xlsx (Excel 2007) data.

We have a excel file whose content are as shown below. Note here sheet name must be same, means if want to read data from Sheet1. You must take care while writting SQL query because SELECT * FROM [Sheet1$] and SELECT * FROM [sheet1$] are two different queries.

excel data

Vb.NET Code

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If (txtFilePath.HasFile) Then
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim query As String
Dim connString As String = ""
Dim strFileName As String = DateTime.Now.ToString("ddMMyyyy_HHmmss")
Dim strFileType As String = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower()
 
‘Check file type
If strFileType.Trim = ".xls" Or strFileType.Trim = ".xlsx" Then
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" & strFileName & strFileType))
Else
lblMessage.Text = "Only excel files allowed"
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
Exit Sub
End If
 
Dim strNewPath As String = Server.MapPath("~/UploadedExcel/" & strFileName & strFileType)
 
‘Connection String to Excel Workbook
If strFileType.Trim = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf strFileType.Trim = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End If
 
query = "SELECT * FROM [Sheet1$]"
 
‘Create the connection object
conn = New OleDbConnection(connString)
Open connection
If conn.State = ConnectionState.Closed Then conn.Open()
‘Create the command object
cmd = New OleDbCommand(query, conn)
da = New OleDbDataAdapter(cmd)
ds = New DataSet()
da.Fill(ds)
 
grvExcelData.DataSource = ds.Tables(0)
grvExcelData.DataBind()
 
da.Dispose()
conn.Close()
conn.Dispose()
Else
lblMessage.Text = "Please select an excel file first"
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
End If
End Sub

Note:

While selecting from a sheet be cautious about sheet name. You must use exact sheet name in your selection query.
i.e. SELECT * FROM [Sheet1$] and SELECT * FROM [sheet1$] are two different queries.
 
If you want to select specific column data then modify your query as given below:
SELECT [Country],[Capital] FROM [Sheet1$]
 
You can also used where clause in you query
query = "SELECT [Country],[Capital] FROM [Sheet1$] WHERE [Currency]=’Rupee’"

C#.NET Code

protected void btnUpload_Click(object sender, EventArgs e)
{
if ((txtFilePath.HasFile))
{
 
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();
 
//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
{
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
lblMessage.Text = "Only excel files allowed";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
return;
}
 
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
 
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
 
query = "SELECT * FROM [Sheet1$]";
//query = "SELECT [Country],[Capital] FROM [Sheet1$] WHERE [Currency]=’Rupee’"
//query = "SELECT [Country],[Capital] FROM [Sheet1$]"
 
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
 
grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();
 
lblMessage.Text = "Data retrieved successfully! Total Records:" + ds.Tables[0].Rows.Count;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;
 
da.Dispose();
conn.Close();
conn.Dispose();
}
else
{
lblMessage.Text = "Please select an excel file first";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
}

I have tested above code and got result as shown below:

retrived excel data

Download

Chetan love blogging. He regularly blogs at http://www.tipsntracks.com. You can connect with Chetan on Twitter, Facebook and Google Plus...

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

Great article, very simple and straight forward. A couple of spells that are to be corrected are “containg” –> containing and ‘Recodes’ to Records.

Great stuff, could you show us how to read specific cells in excel on specific sheets.

Comment by Sarfaraz on August 2, 2009 @ 5:38 am

@ Sarfaraz
Thanks for pointing out my mistakes. I will try my best to avoid it in future

Regards
Chetankumar Akarte

Comment by Chetankumar Akarte on August 13, 2009 @ 2:06 am

Very useful article, thank you.

Comment by Matthew I. on September 3, 2009 @ 1:23 am

Thanks For this Code…Its working for me…thanks agann…

Comment by Naveen Kumar on September 17, 2009 @ 1:16 am

thank you so much its working

Comment by kalyani on November 25, 2009 @ 7:07 am

Very Useful article , Solution is very to the point ! Thanks

Comment by Vinay K Singh on January 13, 2010 @ 12:48 pm

thanks a lot buddy, great job!
can you please provide with reading all the sheets from the excel file…

Comment by vikas on March 23, 2010 @ 9:28 am

@ vikas
Sheet name work like table name. If you want to read all the sheets from the excel file, you need to first confirm number of sheets and sheet names.
Note here, If you want to read data from Sheet1. You must take care while writting SQL query because SELECT * FROM [Sheet1$] and SELECT * FROM [sheet1$] are two different queries.

Comment by Chetankumar Akarte on April 4, 2010 @ 1:50 am

Hi All, this solution works when the order & name of sheets are known. What happens when the number of sheets are unknown? Is there a way to handle this. My sheets are unknown. Also i need to read selective columns and not the entire sheet. Thanks

Comment by Prasad Salunke on April 13, 2010 @ 4:07 am

Hi All,

Where is grvExcelData defined? Am I missing something my imports?

Thanks!
Jordan

Comment by jordan on April 14, 2010 @ 10:48 am

@ jordan

“grvExcelData” is the id of your Gridview, In ASP.NET code, by mistake I have used “dtgJobs” as Id instead of “grvExcelData”. Now I have updated ASP.NET code.

Thanks!
Chetan Akarte

Comment by Chetankumar Akarte on April 14, 2010 @ 2:26 pm

Great article, thank you so much

Comment by Deibid on April 16, 2010 @ 9:06 pm

Great Article. How to retrieve columns from multiple worksheet in Excel?.pls help me

Comment by deepa on August 3, 2010 @ 6:19 am

hello Chetankumar, thx for the code, i tried to use but when i try to open the XLSX file in VB.NET i receive the follow error “OleDbException was Unhandled”
can u help me pls? what can I check ?

Comment by marco on September 15, 2010 @ 2:54 am

thanks a lot .very usefull Article Great Help to Developers

Comment by DAKSHA on September 15, 2010 @ 12:57 pm

Nice article, but I was wondering how easy it is to write to an excel file from asp .net? My idea was to create a template document copy that then populate the copy, just not sure the easiest way to do it. Any suggestions would be cool

Comment by Sean on September 16, 2010 @ 1:59 am

Nice article. But will this work if there is no Office installed on the server?

I need to read an .xlsx file from ASP .net application (uploaded by user) but cannot install MS Office on the server.

Thanks

Comment by Chandra on October 26, 2010 @ 9:09 am

thx buddy its very helpful 2 me!!! and also i want to add this .xls or .xlxs file in to sql server 2005 with auto number can u help me!!!

Comment by hrishikesh on April 14, 2011 @ 11:10 pm

How to retrieve a particular cell from excel file in asp.net.

Comment by Mohit on May 7, 2011 @ 1:42 am

Thanks For this Code…Its working..…thanks again
Adnan

Comment by adnan on May 29, 2011 @ 8:58 pm

nice article………solved my problem easily with some small changes……

Comment by Anil Reddy on June 3, 2011 @ 1:10 pm

Great stuff, my challenge is How to read a password protected sheet

Comment by Larry on August 13, 2011 @ 3:46 am

Thanks sir… after a long time i have seen such a nice and helpful code…

Comment by Parmod on September 9, 2011 @ 4:47 am

Hi, Geat article!
Im am using it to read an excel file and store the data into my DB, but I have this error when I saving the data into my BD: “The SQL version is not compatible with the data type’datetime2′”. My excel file has some DateTime fields and I’m using Win7 and VS2010, any idea?… Thanks a lot!

Comment by Memo Lara on September 9, 2011 @ 7:52 am

Nice Article.

but I’m having different kind of issue. when importing any column of mixed type. say few cell have digits in it and few have alphanumeric values. then it automatically skip those alphanumeric values and consider the whole column as of excel sheet as integer type.
I don’t want end user to set datatype of each column before he/she start import.

is there any workaaround for this problem. I’m importing from .xlsx File.

Thanks
Kamal

Comment by Kamal on September 19, 2011 @ 9:15 am

when we load data from excel to gridview the font style, color and other properties of the data changes . Can you plz explain how we can retain the properties such as color of text, font size , format etc ???

Comment by unnie on November 14, 2011 @ 5:58 am

Can you pls provide the code to view any excel file placed in a gridview?

Comment by trish on January 5, 2012 @ 3:38 am

@unnie
Excel style belong to excel only; you need to modify gridview style as per your need.

@Trish
Code is there for download at the end of the article.

Comment by Chetankumar Akarte on January 16, 2012 @ 10:22 pm

Dear All,
My Excel 2010 .xlsx file currept on network drive and showing ZERO size. How it repair.

Sarfraz

Comment by Muhammad Sarfraz on January 24, 2012 @ 12:32 am

Leave a comment

(required)

(required)

*
To prove that you're not a bot, enter this code
Anti-Spam Image