protected void Button1_Click(object sender, EventArgs e)
{
UploadFileAndBind()
}
public void UploadFileAndBind()
{
if (FileUpload1.HasFile)
{
string strFileName = FileUpload1.PostedFile.FileName
string extFile = Path.GetExtension(strFileName ).ToString().ToLower()
if (extFile == ".xls" || extFile == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/Files/" + strFileName))
BindGrid (Server.MapPath ("~/Files/" + strFileName),extFile )
}
else
{
Label1.Text = "File You Are Uploading is not an Excel File."
Label1.Visible = true
}
}
}
public void BindGrid(string filePath, string filetype)
{
string constr = null
string qry = null
if (filetype.Trim() == ".xls")
{
constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""
}
else if (filetype.Trim() == ".xlsx")
{
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""
}
qry = "select * from [Sheet1$]"
OleDbConnection con = new OleDbConnection(constr)
if (con.State == ConnectionState.Closed)
{
con.Open()
}
OleDbCommand cmd = new OleDbCommand(qry,con )
OleDbDataAdapter odp = new OleDbDataAdapter(cmd )
DataSet ds = new DataSet()
odp.Fill(ds)
odp.Dispose()
con.Close()
con.Dispose()
}