Search Web

Friday, September 16, 2011

Get Data from Excel To Sql Server Using Asp.net



Here I am going to show you the step by step process to import data from Excel to SQL Server. To do so follow the below steps :

Step:1 Create Sample Table.

 GO  
 CREATE TABLE [dbo].[Product_Master](  
   [Product_Code] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,  
   [Product_Name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,  
   [Price] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL  
 ) ON [PRIMARY]  
 GO  

Step:2 Create New Web site with new webpage named as Default.aspx (Following is the code contained in the Default.aspx page).

1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
3:  <html xmlns="http://www.w3.org/1999/xhtml">  
4:  <head runat="server">  
5:    <title>Import Excel Data To SQL Server</title>  
6:  </head>  
7:  <body>  
8:    <form id="form1" runat="server">  
9:    <div>  
10:      <asp:Label ID="lblHeading" runat="server" Text="Select File To Upload : "></asp:Label>  
11:      <asp:FileUpload ID="FileUpload1" runat="server" />  
12:      <br />  
13:      <br />  
14:      <asp:Button ID="btnUpload" runat="server" Text="Upload"   
15:        onclick="btnUpload_Click" />     
16:      <asp:Button ID="btnSaveToDB" runat="server" Text="Save To DB"   
17:        onclick="btnSaveToDB_Click" />  
18:        <br /><br />  
19:      <asp:Label ID="lblerror" runat="server" ForeColor ="Red" Text=""></asp:Label>  
20:    </div>  
21:    </form>  
22:  </body>  
23:  </html>  

Step:3 Here is the C# code of the Default.aspx.cs file:

1:  using System;  
2:  using System.Configuration;  
3:  using System.Data;  
4:  using System.Linq;  
5:  using System.Web;  
6:  using System.Web.Security;  
7:  using System.Web.UI;  
8:  using System.Web.UI.HtmlControls;  
9:  using System.Web.UI.WebControls;  
10:  using System.Web.UI.WebControls.WebParts;  
11:  using System.Xml.Linq;  
12:  using System.IO;  
13:  public partial class _Default : System.Web.UI.Page   
14:  {  
15:    protected void Page_Load(object sender, EventArgs e)  
16:    {  
17:    }  
18:    protected void btnUpload_Click(object sender, EventArgs e)  
19:    {  
20:      if (FileUpload1.HasFile)  
21:      {  
22:        var uploadFile = new UploadFile(FileUpload1.FileName);  
23:        try  
24:        {  
25:          FileUpload1.SaveAs(uploadFile.SavePath);  
26:        }  
27:        catch (Exception ex)  
28:        {  
29:          lblerror.Text = "error : "+ex.Message;  
30:        }  
31:       }  
32:    }  
33:    protected void btnSaveToDB_Click(object sender, EventArgs e)  
34:    {  
35:      ImportDataIntoDB idid = new ImportDataIntoDB();  
36:      string count = idid.saveDataToDB();  
37:      if (Convert.ToInt16(count) < 0)  
38:      {  
39:        lblerror.Text = "Error Occurred...";  
40:      }  
41:      UploadFile upFile = new UploadFile();  
42:      upFile.DeleteFileNoException();  
43:    }  
44:  }  

Step:4 In this i call the UploadFile class which is created in a separate class file. This class is used to store uploaded file and also used to generate OleDb connection string as per file selected. Here is the code of UploadFile Class :

1:  using System;  
2:  using System.Data;  
3:  using System.Configuration;  
4:  using System.Linq;  
5:  using System.Web;  
6:  using System.Web.Security;  
7:  using System.Web.UI;  
8:  using System.Web.UI.HtmlControls;  
9:  using System.Web.UI.WebControls;  
10:  using System.Web.UI.WebControls.WebParts;  
11:  using System.Xml.Linq;  
12:  using System.IO;  
13:  ///   
14:  /// Summary description for UploadFile  
15:  ///   
16:  public class UploadFile  
17:  {  
18:    private string savePath;  
19:    public UploadFile()  
20:    {  
21:    }  
22:    public UploadFile(string originalFileName)  
23:    {  
24:      string tempFileName = Guid.NewGuid().ToString("N") + "_" + originalFileName;  
25:      string saveLocation = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FileUploadLocation"]);  
26:      savePath = Path.Combine(saveLocation, tempFileName);  
27:      HttpContext.Current.Session["savePath"] = savePath;  
28:    }  
29:    ///   
30:    /// Temp path used to save the uploaded file  
31:    ///   
32:    public string SavePath  
33:    {  
34:      get  
35:      {  
36:        return savePath;  
37:      }  
38:    }  
39:    ///   
40:    /// Attempt to delete temp file  
41:    ///   
42:    public void DeleteFileNoException()  
43:    {  
44:      savePath = HttpContext.Current.Session["savePath"].ToString();  
45:      if (File.Exists(savePath))  
46:      {  
47:        try  
48:        {  
49:          File.Delete(savePath);  
50:        }  
51:        catch { }  
52:      }  
53:    }  
54:    ///   
55:    /// Return connection strinng based on file extension  
56:    ///   
57:    public string GetOleDbConnectionString()  
58:    {  
59:      savePath = HttpContext.Current.Session["savePath"].ToString();  
60:      var finfo = new FileInfo(savePath);  
61:      if (!finfo.Exists)  
62:      {  
63:        throw new FileNotFoundException(savePath);  
64:      }  
65:      var fileExtension = finfo.Extension.ToLower();  
66:      switch (fileExtension)  
67:      {  
68:        case ".xls":  
69:          return string.Format(ConfigurationManager.AppSettings["xlsOleDBConnection"], savePath);  
70:        case ".xlsx":  
71:          return string.Format(ConfigurationManager.AppSettings["xlsxOleDBConnection"], savePath);  
72:        default:  
73:          throw new NotSupportedException(String.Format("This file type {0} is not supported!", fileExtension));  
74:      }  
75:    }  
76:  }  

Step:5 Now next step is read that file and save the data into sql server. Here is the method which reads the data from excel and save it into sql server database :

1:  public string saveDataToDB()  
2:    {  
3:      int j = 0;  
4:      string strQuery = "SELECT ProductCode,ProductName,ItemCaptionJP,ItemTextJP,IngredientsJP,CountryOfOrigin,HowToStore FROM [Sheet1$]";  
5:      DataTable dt = new DataTable();  
6:      OleDbCommand ocmd = new OleDbCommand(strQuery, oleconn);  
7:      //OleDbDataAdapter da = new OleDbDataAdapter(strQuery, oleconn);  
8:      oleconn.Open();  
9:      OleDbDataReader odr = ocmd.ExecuteReader();  
10:      int i = 0;  
11:      if (odr.HasRows)  
12:      {  
13:        while (odr.Read())  
14:        {  
15:          if (i == 0)  
16:            sb.Append("UPDATE Product_Master set [itemCaption_jp]=N'" + odr["ItemCaptionJP"] + "',[itemText_jp]=N'" + odr["ItemTextJP"].ToString() + "',[ingredients_jp]=N'" + odr["IngredientsJP"].ToString() + "',[countryoforigin_jp]=N'" + odr["CountryOfOrigin"].ToString() + "',[howtostore_jp]=N'" + odr["HowToStore"].ToString() + "' where [alternate_code]='" + odr["ProductCode"].ToString() + "' and Product_Name='" + odr["ProductName"].ToString() + "'");  
17:          else  
18:            sb.Append(";UPDATE Product_Master set [itemCaption_jp]=N'" + odr["ItemCaptionJP"] + "',[itemText_jp]=N'" + odr["ItemTextJP"].ToString() + "',[ingredients_jp]=N'" + odr["IngredientsJP"].ToString() + "',[countryoforigin_jp]=N'" + odr["CountryOfOrigin"].ToString() + "',[howtostore_jp]=N'" + odr["HowToStore"].ToString() + "' where [alternate_code]='" + odr["ProductCode"].ToString() + "' and Product_Name='" + odr["ProductName"].ToString() + "'");  
19:          i++;  
20:        }  
21:        j = UpdatedCommand(sb.ToString());  
22:      }  
23:      return j.ToString();  
24:    }  
25:    #region update,delete,insert data in Database  
26:    public int UpdatedCommand(string strupdatequery)  
27:    {  
28:      int intreturn = 0;  
29:      ClientScriptManager cs = Page.ClientScript;  
30:      Type ty = this.GetType();  
31:      try  
32:      {  
33:        SqlCommand cmdupdatecommand = new SqlCommand();  
34:        transsql = null;  
35:        if (sqlconn.State != ConnectionState.Closed)  
36:        {  
37:          sqlconn.Close();  
38:        }  
39:        sqlconn.Open();  
40:        transsql = sqlconn.BeginTransaction();  
41:        cmdupdatecommand.CommandTimeout = 0;  
42:        cmdupdatecommand.CommandText = strupdatequery;  
43:        cmdupdatecommand.Connection = sqlconn;  
44:        cmdupdatecommand.Transaction = transsql;  
45:        intreturn = cmdupdatecommand.ExecuteNonQuery();  
46:        transsql.Commit();  
47:        if (sqlconn.State != ConnectionState.Closed)  
48:        {  
49:          sqlconn.Close();  
50:        }  
51:        return intreturn;  
52:      }  
53:      catch (SqlException oleex)  
54:      {  
55:        transsql.Rollback();  
56:        strupdatequery = oleex.Message;  
57:        strerorrmsg1 = "Error In UpdatedCommand method " + oleex.Message.ToString();  
58:        strerorrmsg2 = strerorrmsg1.Replace("'", "");  
59:        string msg = "alert('" + strerorrmsg2 + "');";  
60:        cs.RegisterStartupScript(ty, strerorrmsg1, msg, true);  
61:        return -3;  
62:      }  
63:      catch (System.Exception exp)  
64:      {  
65:        transsql.Rollback();  
66:        strupdatequery = exp.Message;  
67:        strerorrmsg1 = "Error In UpdatedCommand method " + exp.Message.ToString();  
68:        strerorrmsg2 = strerorrmsg1.Replace("'", "");  
69:        string msg = "alert('" + strerorrmsg2 + "');";  
70:        cs.RegisterStartupScript(ty, strerorrmsg1, msg, true);  
71:        return -3;  
72:      }  
73:      finally  
74:      {  
75:        if (sqlconn.State != ConnectionState.Closed)  
76:        {  
77:          sqlconn.Close();  
78:        }  
79:      }  
80:    }  
81:    #endregion   

0 comments:

Post a Comment