June 17, 2015

Upload Excel Sheet data to Sql Server in Asp.net

protected void btnUpload_Click(object sender, EventArgs e)
{
        if (FileUpload1.HasFile)
        {
            string sPath = Server.MapPath("~/BulkFolder/" + FileUpload1.FileName);
            FileUpload1.SaveAs(sPath);

            ImporttoSQL(sPath);
        }
}


private void ImporttoSQL(string sPath)
    {
        try
        {
       
            string sSourceConstr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);

            string sDestConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
            using (sSourceConnection)
            {
                string sql = string.Format("Select [Sno],[Subject],[Question],[op1],[op2],[op3],[op4],[Answer] FROM [{0}]", "Sheet1$");
                OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
                sSourceConnection.Open();
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
                    {
                        bulkCopy.DestinationTableName = "Questions";
                       
                        bulkCopy.WriteToServer(dr);
                        Label1.Visible = true;
                    }
                }
            }
        }
        catch (Exception y)
        {
            Label1.Visible = true;
            Label2.Visible = true;
            Label3.Visible = true;
            Label1.Text = "Cannot upload the quetions. Please check that";
            Label2.Text = "1. All the values are present. No column is missing.";
            Label3.Text = "2. Answer is in the numeric value or file format is wrong.";
        }

    }

Html Code


    Untitled Page
   

   

 
               

               
                    
                              


                                   Question storage


                              
                                                                          NavigateUrl="~/Faculty/Default.aspx">Home
                              

    Formats allowed

       
                  
           

                   
  • File format with 2003.

  •                
  • File format with 2007.

  •                                           
  • File format with 2010.

  •            
 
       

       

   

   
          
   
       

                    Visible="False">
   

       

                                  
       

                                  
       

       

                        
       

   


Output

No comments:

Post a Comment