Monday, June 24, 2013

How to copy excel to database in asp.net C# ?

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.SqlClient;

using System.Configuration;

public partial class copyextodatabase : System.Web.UI.Page



{

protected void Page_Load(object sender, EventArgs e)



{

}

protected void Button1_Click(object sender, EventArgs e)



{

string connStringExcel = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\blossom.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";

OleDbConnection excelConn = new OleDbConnection(connStringExcel);

OleDbCommand excelCmd = new OleDbCommand("Select * From [Sheet2$]", excelConn);

try



{

excelConn.Open();

OleDbDataReader excelReader = excelCmd.ExecuteReader();

string connStringSql = ConfigurationManager.ConnectionStrings["cn"].ToString();

SqlConnection sqlConn = new SqlConnection(connStringSql);

try



{

sqlConn.Open();

SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);

bulkCopy.DestinationTableName = "BT";



bulkCopy.WriteToServer(excelReader);

Label1.Text = "Data successfully copied to SQL Server database table";



}

catch (Exception exs)



{

Label1.Text = exs.Message;

}

finally



{

sqlConn.Close();

}

}

catch (Exception exo)



{

Label1.Text = exo.Message;

}

finally



{

excelConn.Close();

}

}



}


No comments:

Post a Comment