hello dear
as i am just a newbie in this field and trying to learn what ever i can
i did implement this concept in one of my project.
not sure but may be there is a problem with the type of the file Code expect you to upload
there are two or may be more type of MS Excel files are there
1. with the extension .xls (MS Excel 2003 may be)
2. with the extension .xlsx (MS Excel 2007 i think)
you can rewrite the code as below : to check if the code working properly or not do the following procedure
open a new website or project in the asp.net (what ever version you are using )
now add the following controls on the Design window :
1. Label1 (set its visible property to false)
2. Label2 (set its visible property to false)
3. FileUpload1
4. a button control with the text SHowData
5. and a gridview1
6. create a new folder in the current directory name it Files
now goto the code window and add the following code there :
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)
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0]
GridView1.DataBind()
}
}
else
{
Label2.Text = "No Data To Show"
Label2.Visible = true
}
odp.Dispose()
con.Close()
con.Dispose()
}
it works for me but even if you got any problem let me know
GOD help Programmers.
best regards