Tuesday, March 15, 2011

READING EXCEL SHEET DATA INTO DATABASE TABLE USING BULK UPLOAD

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
//        string excelConnectionString = @"Provider=Microsoft
//    .Jet.OLEDB.4.0;Data Source=C:\Users\CRM5\Desktop\demo.xls;Extended
//    Properties=""Excel 8.0;HDR=YES;""";


        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\CRM5\Desktop\Book1.xlsx;Extended Properties=Excel 12.0";



      //Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + strPath + ";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES

// 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=.; Initial Catalog=test;Integrated Security=True";

        // Bulk Copy to SQL Server
        using (SqlBulkCopy bulkCopy =
                   new SqlBulkCopy(sqlConnectionString))
        {
            bulkCopy.DestinationTableName = "demo";// sql server databse =test table= demo
            bulkCopy.WriteToServer(dr);
        }
    }
}
    }
 
}

No comments:

Post a Comment