Monday, April 25, 2011

Import Bulk Data to SQL Server Using SqlBulkCopy

Import Bulk Data to SQL Server Using SqlBulkCopy

using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;

Public class bulkcopyTest
{

Public void bulkcopyTestEG(DataTable dtEmport)
{

try
{
OleDbConnection Con = CreateConnection("Connection_String");

//Open bulkcopy connection.
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(Con))
{
//Set destination table name
//to table previously created.
bulkcopy.DestinationTableName = "Bulk_Copy_Test";

try
{
bulkcopy.WriteToServer(dtEmport);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}
}
}
}

Import Data from Excel in SQL server.

Import Data from Excel in SQL server.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.ComponentModel;
namespace ExcelImport
{
public class ExcelBase : Component, IDisposable
{
///
/// Creates a NEW connection. If this method is called directly, this
/// class will not check if it is closed.
/// To get a handled connection, use the property.
///

///
public OleDbConnection CreateConnection()
{
return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties="Excel 12.0;HDR=YES");
}
public DataTable GetDataFromExcel()
{
try
{
OleDbConnection Conn = CreateConnection();

DataTable dt = new DataTable();

OleDbDataAdapter DA = new OleDbDataAdapter("Select * From [Sheet1$]",Conn);

DA.Fill(dt);

return dt;
}
finally
{
CloseConnection(true);
}
}
}