Code Snippet posted by:
Bageshkumarbagi | Posted on: 10/10/2012 | Category:
ASP.NET Codes | Views: 786 | Status:
[Member] |
Points: 40
|
Alert Moderator
Html Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication6._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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2">
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
C# code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace WebApplication6
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string file = Server.MapPath("msxcel.xls");
string connStr = string.Format(ConfigurationManager.AppSettings["Excel2003OleDBConnection"], file);
DataTable table = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connStr))
{
string sheet = @"SELECT * FROM [Sheet1$]";
// to avoid error write the sheet name in square bracket
using (OleDbCommand cmd = new OleDbCommand(sheet, conn))
{
conn.Open();
using (OleDbDataAdapter ad = new OleDbDataAdapter(cmd))
{
ad.Fill(table);
}
conn.Close();
};
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
}
you should need to copy below code in web.config file
<appSettings>
<add key="Excel2003OleDBConnection" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 8.0;HDR=YES;IMEX=1""/>
<add key="Excel2007OleDBConnection" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1""/>
</appSettings>
you should need to create a ms Excel file in Solution explorer whic name is msxcel.xls
Enjoy it.
If you have any doubt feel free to contact me at
bageshkumarbagiasp.net@gmail.com
Found interesting? Add this to: