anjali khan

anjali khan

  • NA
  • 293
  • 65.7k

how to display excel file data in gridview?

Aug 12 2015 7:06 AM

hi Friends

i am sending the code please check it...

please dont share me any link once check this and tell me where i did mistake..

design page///

<div style="width:100%; text-align:center">
      <h3>GridView with Excel File </h3>
      <asp:FileUpload ID="fileupload1" runat="server" />
      <br /><br />
      <asp:Button ID="btnupload" runat="server" OnClick="btnupload_click" Text="Upload" />
      <br /><br />
      <asp:Label ID="lbl1" runat="server"></asp:Label>
      <br />
      <asp:GridView ID="gvexcel" runat="server" Width="100%" Font-Bold="true" AlternatingRowStyle-BackColor="Chocolate"></asp:GridView>
    </div>

code///

protected void btnupload_click(object sender, EventArgs e)
        {
         string connString = "";

        string strFileType = Path.GetExtension(fileupload1.FileName).ToLower();

        string path = fileupload1.PostedFile.FileName;

        if (strFileType.Trim() == ".xls")
        {

          connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:\\Bio Rad\\exceldata.xlsx ;Extended Properties=\"Excel 8.0\""; 

           // connString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source= D:\\Bio Rad\\exceldata.xlsx;Extended Properties=\"Excel  12.0 ;HDR=YES\"";
        }
        string query = "Select [Patient ID],[Assay],[Well],[Flag],[Value],[S/CO],[Result] from Exceldata";       

        OleDbConnection conn = new OleDbConnection(connString);
     
        if (conn.State == ConnectionState.Closed)
  
         conn.Open();
 
        OleDbCommand cmd = new OleDbCommand(query, conn);

        OleDbDataAdapter da = new OleDbDataAdapter(cmd);

        DataSet ds = new DataSet();

        da.Fill(ds);

        gvexcel.DataSource = ds.Tables[0];

        gvexcel.DataBind();

        da.Dispose();

        conn.Close();

        conn.Dispose();
        }
    }


Answers (20)