Tuesday, April 14, 2009

Import data from Excel to SQl Server

Facing problem while importing table data from Excel to Sql Server.
Some time we have some fields on Excel which contain data which is not supported by
Sql Server like single qote('). I take it just as a example. So i write a program
in c# which collects data from excel table read it make changes on data if we need and insert it to SQL. Problem is basically
that if we have lakhs of record its not possible to edit them manually and then import to sql.

public partial class _Default : 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=YourExcelDataSource(like D:\\Detail.xls);Extended Properties=""Excel 8.0;HDR=YES;""";
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Data$]", connection);

connection.Open();
DataSet ds = new DataSet();

OleDbDataAdapter oda = new OleDbDataAdapter(command);
oda.Fill(ds);

string sqlConnectionString = "Data Source= SqlDataSource; Initial Catalog=DataBaseName;uid=Userid; Password=pwd";

SqlConnection con = new SqlConnection(sqlConnectionString);
con.Open();

for (int c = 0;c < ds.Tables[0].Rows.Count;c++)
{
try
{
DataRow dro = ds.Tables[0].Rows[c];

object[] array = ds.Tables[0].Rows[c].ItemArray; //Break Table to array

string str = "insert into tableName values(";

for (int k = 1; k < array.Length; k++)
{
if (array[k].ToString().Contains("'"))
{
array[k] = array[k].ToString().Replace("'", "''");
}

str = str+"'"+ array[k] + "',";
}


str = str.Substring(0, str.Length - 1);
str = str + ")";
SqlCommand com = new SqlCommand(str);
com.Connection = con;
com.ExecuteNonQuery();
}
catch(Exception ex)
{
continue;
}
}
//}
}
}
}

No comments:

Post a Comment