Wednesday, April 6, 2011

Import Excel Spreadsheet Data into SQL Server Database Table Using SqlBulkCopy

In Web Config:
AppSettings :

add key="Excel2003SqlConnection" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 8.0;HDR=YES;IMEX=1"">
add key="Excel2007SqlDBConnection" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1"">
add key="FileUploadLocation" value="~/ExcelFilesUploaded/Temp"/>



Funtction to Upload Excel Files:

public void UploadExcelFileToDataBase(string DestServer, string DestDatabase, string DestUserID, string DestPassword, string destinationtableName, string ExcelSheetRange,FileUpload fileUpload1,Label label1)
{
try
{

if (fileUpload1.HasFile)
{
//the location is given in the web.config file's Appsettings.
string SaveLocation = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FileUploadLocation"]);
string location = SaveLocation + fileUpload1.FileName;
fileUpload1.SaveAs(location);

string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source= " + location + ";" + "Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(xConnStr))
{

OleDbCommand command = new OleDbCommand("Select * FROM " + ExcelSheetRange + "", connection);

connection.Open();

//delete all previous records from the table.

SQLHelper objSql = new SQLHelper();
objSql.SqlText = "Delete from " + destinationtableName;
objSql.ExecuteSql(false);
objSql.Close();
objSql.Dispose();

// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string ConnString = "server = " + DestServer + "; database = " + DestDatabase + "; user id= " + DestUserID + ";password=" + DestPassword;
string sqlConnectionString = ConnString;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = destinationtableName;

bulkCopy.WriteToServer(dr);

}
}
}
label1.Visible = true;
label1.Text = "Data Uploaded Successfully on " + destinationtableName;
}
}
catch (Exception ex)
{
label1.Text = ex.ToString();
}
}

1 comment:

Anonymous said...

sFileConnectionString:Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\inetpub\wwwroot\localuser\vito21637\www/backadmin/ExcelUploadData/nl_clients_5.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";
Error No:-2147418113
Error Description:Catastrophic failure