<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadExcel.aspx.cs" Inherits="Practice2010.UploadExcel" %><!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></title></head><body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpdExcel" runat="server" /> <asp:Button ID="btnDisplay" runat="server" onclick="btnDisplay_Click" Text="Display Data" /> <br /> <asp:GridView ID="grdExcel" runat="server"> </asp:GridView> <br /> <asp:Label ID="lblMsg" runat="server"></asp:Label> </div> </form></body></html>
<add name ="ExcelCon2003" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'"/>
<add name ="ExcelCon2007" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'"/>
<appSettings> <add key ="UploadFolderPath" value ="Upload/"/></appSettings >
using System.IO;using System.Data;using System.Data.OleDb;
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Data;using System.Data.OleDb;namespace Practice2010{ public partial class UploadExcel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnDisplay_Click(object sender, EventArgs e) { if (FileUpdExcel.HasFile) { string strExcelFileName = Path.GetFileName(FileUpdExcel.PostedFile.FileName); string strfileExt = Path.GetExtension(FileUpdExcel.PostedFile.FileName); string FolderPath = System.Configuration.ConfigurationManager. AppSettings["UploadFolderPath"]; string FilePath = Server.MapPath(FolderPath + strExcelFileName); FileUpdExcel.SaveAs(FilePath); string strConString = string.Empty; if (strfileExt == ".xls") { strConString = System.Configuration.ConfigurationManager. ConnectionStrings["ExcelCon2003"].ConnectionString; } else { strConString = System.Configuration.ConfigurationManager. ConnectionStrings["ExcelCon2007"].ConnectionString; } strConString = String.Format(strConString, FilePath); OleDbConnection oledbCon = new OleDbConnection(strConString); try { oledbCon.Open(); OleDbCommand oledbCmd = new OleDbCommand("select * from [Sheet1$]", oledbCon); OleDbDataAdapter oledbDa = new OleDbDataAdapter(); oledbDa.SelectCommand = oledbCmd; DataSet dsExcel = new DataSet(); oledbDa.Fill(dsExcel, "Employee"); grdExcel.DataSource = dsExcel.Tables[0].DefaultView; grdExcel.DataBind(); } catch (Exception ex) { string strError = ex.Message; lblMsg.Text = strError; } finally { oledbCon.Close(); } } } }}