Thursday, July 17, 2008

Exporting Data From Excel to SqlServer

Following are the ways to export data from excel to sql server
1)With SQLBulkCopy
create file info.xls and create table in respective database named ExcelData
Source code as follows
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
public partial class ExportFromExcelToSQL : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


// Connection String to Excel Workbook

string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\excel\Info.xls;Extended Properties=Excel 8.0";


// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);


connection.Open();

// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())

{

// SQL Server Connection String
string sqlConnectionString = "Data Source=ITCUBE-4M1HVRHY; Initial Catalog=ITC;User ID=cp;Password=cp;";

// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "dbo.ExcelData";
bulkCopy.WriteToServer(dr);
}
}
}




}
}

2)With DTS utility of SQL

No comments: