Import Data from Excel to SQL Server using ASP.Net


Many times we need to import data from excel sheet to Sql Server data base in our web application. So Here I am going to show you the step by step process to import data from Excel to SQL Server. In this article you will get the code for uploading the excel file into server and then import data from that file into SQL Server. How to import Data from Excel to SQL Server using ASP.Net?

How to Import 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 a 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).

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Import Excel Data To SQL Server</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblHeading" runat="server" Text="Select File To Upload : "></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
<asp:Button ID="btnSaveToDB" runat="server" Text="Save To DB"
onclick="btnSaveToDB_Click" />
<br /><br />
<asp:Label ID="lblerror" runat="server" ForeColor ="Red" Text=""></asp:Label>
</div>
</form>
</body>
</html>


Step 3 :


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


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
var uploadFile = new UploadFile(FileUpload1.FileName);
try
{
FileUpload1.SaveAs(uploadFile.SavePath);

}
catch (Exception ex)
{
lblerror.Text = "error : "+ex.Message;
}
}
}
protected void btnSaveToDB_Click(object sender, EventArgs e)
{
ImportDataIntoDB idid = new ImportDataIntoDB();
string count = idid.saveDataToDB();
if (Convert.ToInt16(count) < 0)
{
lblerror.Text = "Error Occurred...";
}
UploadFile upFile = new UploadFile();
upFile.DeleteFileNoException();
}

}


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 :


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

///
/// Summary description for UploadFile
///

public class UploadFile
{
private string savePath;
public UploadFile()
{

}
public UploadFile(string originalFileName)
{
string tempFileName = Guid.NewGuid().ToString("N") + "_" + originalFileName;
string saveLocation = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FileUploadLocation"]);
savePath = Path.Combine(saveLocation, tempFileName);
HttpContext.Current.Session["savePath"] = savePath;
}
///
/// Temp path used to save the uploaded file
///

public string SavePath
{
get
{
return savePath;
}
}
///
/// Attempt to delete temp file
///

public void DeleteFileNoException()
{
savePath = HttpContext.Current.Session["savePath"].ToString();
if (File.Exists(savePath))
{
try
{
File.Delete(savePath);
}
catch { }
}
}

///
/// Return connection strinng based on file extension
///

public string GetOleDbConnectionString()
{
savePath = HttpContext.Current.Session["savePath"].ToString();
var finfo = new FileInfo(savePath);

if (!finfo.Exists)
{
throw new FileNotFoundException(savePath);
}

var fileExtension = finfo.Extension.ToLower();
switch (fileExtension)
{
case ".xls":
return string.Format(ConfigurationManager.AppSettings["xlsOleDBConnection"], savePath);
case ".xlsx":
return string.Format(ConfigurationManager.AppSettings["xlsxOleDBConnection"], savePath);
default:
throw new NotSupportedException(String.Format("This file type {0} is not supported!", fileExtension));
}
}
}


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 :

public string saveDataToDB()
{
int j = 0;
string strQuery = "SELECT ProductCode,ProductName,ItemCaptionJP,ItemTextJP,IngredientsJP,CountryOfOrigin,HowToStore FROM [Sheet1$]";
DataTable dt = new DataTable();
OleDbCommand ocmd = new OleDbCommand(strQuery, oleconn);
//OleDbDataAdapter da = new OleDbDataAdapter(strQuery, oleconn);
oleconn.Open();
OleDbDataReader odr = ocmd.ExecuteReader();
int i = 0;
if (odr.HasRows)
{
while (odr.Read())
{
if (i == 0)
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() + "'");
else
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() + "'");
i++;
}
j = UpdatedCommand(sb.ToString());
}
return j.ToString();
}
#region update,delete,insert data in Database
public int UpdatedCommand(string strupdatequery)
{
int intreturn = 0;
ClientScriptManager cs = Page.ClientScript;
Type ty = this.GetType();
try
{
SqlCommand cmdupdatecommand = new SqlCommand();
transsql = null;
if (sqlconn.State != ConnectionState.Closed)
{
sqlconn.Close();

}
sqlconn.Open();
transsql = sqlconn.BeginTransaction();
cmdupdatecommand.CommandTimeout = 0;
cmdupdatecommand.CommandText = strupdatequery;
cmdupdatecommand.Connection = sqlconn;
cmdupdatecommand.Transaction = transsql;
intreturn = cmdupdatecommand.ExecuteNonQuery();
transsql.Commit();
if (sqlconn.State != ConnectionState.Closed)
{
sqlconn.Close();

}
return intreturn;

}
catch (SqlException oleex)
{
transsql.Rollback();
strupdatequery = oleex.Message;
strerorrmsg1 = "Error In UpdatedCommand method " + oleex.Message.ToString();
strerorrmsg2 = strerorrmsg1.Replace("'", "");
string msg = "alert('" + strerorrmsg2 + "');";
cs.RegisterStartupScript(ty, strerorrmsg1, msg, true);


return -3;
}
catch (System.Exception exp)
{
transsql.Rollback();
strupdatequery = exp.Message;
strerorrmsg1 = "Error In UpdatedCommand method " + exp.Message.ToString();
strerorrmsg2 = strerorrmsg1.Replace("'", "");
string msg = "alert('" + strerorrmsg2 + "');";
cs.RegisterStartupScript(ty, strerorrmsg1, msg, true);
return -3;


}
finally
{
if (sqlconn.State != ConnectionState.Closed)
{
sqlconn.Close();

}

}
}
#endregion


Reference: http://dotnetsquare.com/resources/44-import-data-from-excel-to-sql-server-using-Asp-Net


Article by Manoranjan Sahoo
If it helps you then Rate this. Best Regards, Manoranjan Sahoo http://www.dotnetsquare.com Blog: http://blog.msahoo.net

Follow Manoranjan Sahoo or read 63 articles authored by Manoranjan Sahoo

Comments

Author: Md Aneesuddin Arif14 Sep 2011 Member Level: Silver   Points : 1

Thank you very much Manoranjan Sahoo.

I need little more assistance from you.

Can you tell whether above code will work for Oracle 10g database also ? If no then what changed we need to make to meet the requirement.

If you have any code or application for Oracle database importing Please send it to me on toanees@gmail.com .

Thank in Advance for your Time.

Regards
Arif

Author: srirama13 Apr 2013 Member Level: Gold   Points : 2

Hi,

You are taking a datareader which is a connection oriented.How many rows You made the connection alive whay can n't take datable and update the things for insert you can directly go for sqlbulkcopy.or you can change the datatable convert into xml and then sent to sqldatabase.

Author: naveensanagasetti11 Sep 2013 Member Level: Gold   Points : 10

Hi,

We can do this in no.of ways. Same concept i did in different format.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcelToSQL.aspx.cs" Inherits="ExportExcelToSQL" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title>< /title>
< style type="text/css">
.style1
{
width: 420px;
}
< /style>
< /head>
< body>
< form id="form1" runat="server">
< div>

< table width="100%">
< thead>
< tr>
< td colspan="4" align="center" style="font-size:xx-large; font-style:italic; color:Red">
Export Excel To SQL
< /td>
< /tr>
< tr>

< td>< /td>
< /tr>
< tr>

< td>< /td>
< /tr>
< /thead>

< tbody>
< tr>
< td colspan="3" align="right">
< asp:FileUpload ID="FileUpload1" runat="server" Width="354px"
style="margin-left: 0px" />
< /td>
< td colspan="1" width="30%">
< asp:Button ID="btnView" runat="server" Text="View" onclick="btnView_Click" />
< /td>
< /tr>
< tr>
< td colspan="3" align="right">
< asp:DropDownList ID="ddlSheet" runat="server" AutoPostBack="True" Width="49%" Visible="false"
Height="18px" OnSelectedIndexChanged="ddlSheet_OnSelectedIndexChanged">
< /asp:DropDownList>
< /td>
< td colspan="1" width="30%">

< /td>
< /tr>
< tr>
< td colspan="3" align="center">

< asp:Button ID="btnShow" runat="server" Text="Show" Visible="false"
onclick="btnShow_Click" />
< /td>
< td colspan="1" width="30%">
< asp:Button ID="btnInsert" runat="server" Text="Insert To SQL DB"
Visible="false" onclick="btnInsert_Click" />
< /td>
< /tr>

< tr>
< td>< /td>
< td class="style1">< /td>
< /tr>
< tr>
< td>< /td>
< td class="style1">< /td>
< /tr>
< tr>
< td colspan="4" width="100%" align="center">
< asp:GridView ID="gvExcelData" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" >
< AlternatingRowStyle BackColor="White" />
< EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />

</asp:GridView>
<br />
<asp:Label ID="lblResult" runat="server"></asp:Label>

</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>



Code Behind:

1) using System.Data.OleDb; , using this namespace we can read the excel sheet data.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

public partial class ExportExcelToSQL : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
//here it's fetching all sheets available in excel book
private void Get_Sheets()
{
OleDbConnection oconn = null;
DataTable dt = null;
try
{
string FilePath = string.Empty;
string FileName = string.Empty;
if (FileUpload1.HasFile)
{
//Get File name
FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
// Get File extension
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = "~/ExcelSheets/";
FilePath = Server.MapPath(FolderPath + FileName);
ViewState["FilePath"] = FilePath;
ViewState["FileName"] = FileName;
//File save
FileUpload1.SaveAs(FilePath);
}
//Microsoft Office 12.0 Access Database Engine OLE DB Provider
oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0");

oconn.Open();
dt = null;
// Get all tables include in that work sheet
dt = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{

}
String[] sheet = new String[dt.Rows.Count];
int i = 0;

//Read All sheet names and store in one string Builder

foreach (DataRow dr in dt.Rows)
{
sheet[i] = dr["TABLE_NAME"].ToString();
i++;
}

string[] a = sheet;
int j = 0;

// Assign all sheet names to DropDownList

if (a != null && a.Length > 0)
{
ddlSheet.Visible = true;
//lblsheet.Visible = true;
for (j = 0; j < a.Length; j++)
{
ddlSheet.Items.Add(a[j]);
}
//Default selected value for DropDown
ddlSheet.Items.Insert(0, "<--- Select Excel Sheet --->");
}
else
{
ddlSheet.Visible = false;
//lblsheet.Visible = false;
}
}
catch (Exception ex)
{
}
finally
{
//Close the connection
if (oconn != null)
{
oconn.Close();
oconn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

// Using this button we fetch all sheets included in WrkBook
protected void btnView_Click(object sender, EventArgs e)
{
Get_Sheets();
}
protected void ddlSheet_OnSelectedIndexChanged(object sender, EventArgs e)
{
btnShow.Visible = true;
}
//Using this we display Excel sheet data into GridView control
private void Display()
{
OleDbConnection oconn = null;
DataTable dt1 = new DataTable();

//Add dummy columns to datatable.

dt1.Columns.Add("ENAME");
dt1.Columns.Add("JOB");
dt1.Columns.Add("MGR");
dt1.Columns.Add("SAL");
dt1.Columns.Add("COMM");
try
{
string FileName = ViewState["FileName"] as string;
string FilePath = ViewState["FilePath"] as string;

oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0");

//select file name based upon dropdown selecteditem.

OleDbCommand ocmd = new OleDbCommand("select * from [" + ddlSheet.SelectedItem.ToString() + "]", oconn);

oconn.Open();

//Read all rows and then store in DataTable

OleDbDataReader odr = ocmd.ExecuteReader();
string ENAME=string.Empty;
string JOB=string.Empty;
string MGR=string.Empty;
string SAL=string.Empty;
string COMM=string.Empty;
while (odr.Read())
{
ENAME = odr["ENAME"].ToString();
JOB = odr["JOB"].ToString();
MGR = odr["MGR"].ToString();
SAL = odr["SAL"].ToString();
COMM = odr["COMM"].ToString();

DataRow dr = dt1.NewRow();
dr["ENAME"] = ENAME;
dr["JOB"] = JOB;
dr["MGR"] = MGR;
dr["SAL"] = SAL;
dr["COMM"] = COMM;
dt1.Rows.Add(dr);
}

//Display data to gridview if Records are found

if (dt1.Rows.Count > 0)
{
Session["Table"] = dt1;
gvExcelData.Visible = true;
gvExcelData.DataSource = dt1;
gvExcelData.DataBind();

}
}
catch (DataException ex)
{
}
finally
{
if (oconn != null)
{
oconn.Close();
oconn.Dispose();
}
if (dt1 != null)
{
dt1.Dispose();
}
}
}
//here it's displaying all the records into one gridview control
protected void btnShow_Click(object sender, EventArgs e)
{
btnInsert.Visible = true;
Display();
}
private void InsertIntoDB()
{
int count=0;

SqlConnection con = new SqlConnection("DataBase=ENGSOFT;User Id=sa;Password=P@ssword9");
try
{
con.Open();
SqlCommand cmd;
DataTable dt = Session["Table"] as DataTable;


if (dt.Rows.Count > 0)
{
//Read each and everyrow of datatable and insert each and every row to SQL DataBase.
foreach (DataRow dr in dt.Rows)
{
string Ename = dr["ENAME"].ToString();
string Job = dr["JOB"].ToString();
string MGR = dr["MGR"].ToString();
string Sal = dr["SAL"].ToString();
string comm = dr["COMM"].ToString();

//normal insert query.

cmd = new SqlCommand("INSERT INTO EMP(ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) VALUES(@ename,@job,@mgr,@hiredate,@sal,@comm,@deptno)", con);
cmd.Parameters.AddWithValue("@ename", Ename);
cmd.Parameters.AddWithValue("@job", Job);
cmd.Parameters.AddWithValue("@mgr", MGR);
cmd.Parameters.AddWithValue("@hiredate", DateTime.Now);
cmd.Parameters.AddWithValue("@sal", Sal);
cmd.Parameters.AddWithValue("@comm", comm);
cmd.Parameters.AddWithValue("@deptno", "1");

int n = cmd.ExecuteNonQuery();
count = count + n;

}
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
con.Dispose();
lblResult.Text = count + " Records Inserted Successfully...!!!";
}
}
//here total records inserted into sql database
protected void btnInsert_Click(object sender, EventArgs e)
{
InsertIntoDB();
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: