Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Import Data from excel to SQL server using C# in ASP. NET

0.00/5 (No votes)
16 Dec 2011 2  
When the user uploads the Excel file to the server its data must dumped to the SQL server database
The Page having a FileUpload control and the Upload button, on selecting the Excel file user needs to click on Upload button to store the data to Server. Here we are treating the uploaded file as database hence we need to create OLEDB connection to this file, from this connection will be created and the data is fetched to C# as DataTable. '[Sheet1$]' is the Name of the Worksheet where requires data is present.
C#
string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +  + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);

From this code connection will be created for the Excel file and the data in Sheet1 will be dumped to the dtExcel of type DataTable.
Note:'$' must be there after the worksheet name.

Whole code for the same is here.
C#
fileName = FileUpload1.ResolveClientUrl(FileUpload1.PostedFile.FileName);
int count = 0;
DataClassesDataContext conLinq = new DataClassesDataContext("Data Source=server name;Initial Catalog=Database Name;Integrated Security=true");
try
{
   DataTable dtExcel = new DataTable();
   string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
   OleDbConnection con = new OleDbConnection(SourceConstr);
   string query = "Select * from [Sheet1$]";
   OleDbDataAdapter data = new OleDbDataAdapter(query, con);
   data.Fill(dtExcel);
   for (int i = 0; i < dtExcel.Rows.Count; i++)
   {
      try
      {
         count += conLinq.ExecuteCommand("insert into table name values(" + dtExcel.Rows[i][0] + "," + dtExcel.Rows[i][1] + ",'" + dtExcel.Rows[i][2] + "',"+dtExcel.Rows[i][3]+")");
      }
      catch (Exception ex)
      {
         continue;
      }
   }
   if (count == dtExcel.Rows.Count)
   {
      <--Success Message-->
   }
   else
   {
      <--Failure Message-->
   }
}
catch (Exception ex)
{
   throw ex;
}
finally
{
   conLinq.Dispose();
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here