Wednesday 23 November 2011

Importing data from excel 2003 file in a gridview in asp.net

In Asp.net you have to upload file from client side from fileupload control and save particular file in a server folder and then use this code and changes the file name( Book1.xls) as your file name as on your server.mappath folder file.
     
For Excel file 2003 only:- 
   

    private void btnImportExcelToGridview_Click(object sender, System.EventArgs e)
    {

        String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
        "Data Source="+Server.MapPath(@"File/Book1.xls")+
        "Extended Properties=Excel 8.0;";

        DataSet ds = new DataSet();
        //You must use the $ after the object
        //you reference in the spreadsheet
        OleDbDataAdapter da = new OleDbDataAdapter
        ("SELECT * FROM [Sheet1$]", strConn);

         da.Fill(ds);
         Gridview1.DataSource = ds.Tables[0].DefaultView;
         Gridview1.DataBind();
    }

No comments:

Post a Comment