Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to convert the data from excel to sql server2005..?
please any one can help me its urgent........
Posted

Hi,

try this code,

C#
string CSVFileName=@"D:\filename.csv";
string Datasetname="TableName";
CSVConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyPath + ";Extended Properties='text;HDR=Yes;FMT=Delimited";
string DBSqlServerConstringSQLAuth="Password=password;Connection Timeout=0;Persist Security Info=False;User ID=userid;Initial Catalog=databasename;Data Source=servername";
SqlConnection sqlConnection = new SqlConnection(DBSqlServerConstringSQLAuth);
private void LoadDataToDatabase(string CSVFileName, string Datasetname, string CSVConnectionString)
        {
            LAHDALClass objLAHDALClass = new LAHDALClass();
            DataTable CSVDataTable = GetCsvfileColumns(CSVFileName, CSVConnectionString);
            
	try
	{
            SqlBulkCopy bc = new SqlBulkCopy(sqlConnection.DBSqlServerConstringSQLAuth, SqlBulkCopyOptions.TableLock);
            sqlConnection.Open();
            
            bc.DestinationTableName = Datasetname;
            bc.BatchSize = CSVDataTable.Rows.Count;
            bc.WriteToServer(CSVDataTable);
	}
            catch (Exception ex)
            {
                throw ex;
            }
              finally
                {
                    sqlConnection.Close();
                    bc.Close();
                }
         }

public DataTable GetCsvfileColumns(string CSVFileName,string CSVConnectionString)
        {

            CsvText = "select * from [" + CSVFileName + "]";
            DataTable dataTable = new DataTable();
            DataTable dtSchema = new DataTable();

            OleDbConnection Con = new OleDbConnection(CSVConnectionString);
            try
            {
                OleDbDataAdapter adptr = new OleDbDataAdapter(CsvText, Con);
                dataTable.Locale = CultureInfo.CurrentCulture;
                adptr.FillSchema(dataTable, SchemaType.Mapped);
                adptr.Fill(dataTable);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (Con != null)
                    Con.Dispose();
            }
            return dataTable;
        }
 
Share this answer
 
v2
 
Share this answer
 
1.Write code for excel file into Data table.
C#
public static DataTable exceldata(string filePath)
        {     
            DataTable dtexcel = new DataTable();
               bool hasHeaders = false;
                string HDR = hasHeaders ? "Yes" : "No";
                string strConn;
                if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
                else
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });                
                DataRow schemaRow = schemaTable.Rows[0];
                string sheet = schemaRow["TABLE_NAME"].ToString();
                if (!sheet.EndsWith("_"))
                {
                    string query = "SELECT  * FROM [" + sheet + "]";
                    OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                    dtexcel.Locale = CultureInfo.CurrentCulture;
                    daexcel.Fill(dtexcel);
                }
            
            conn.Close();
            return dtexcel;

        }


2.Through Bulk Copy u can insert data table into Sql database table.

C#
public void BulkImport(DataTable ExcelDatatable, string TABLENAME)
        {

            if (ExcelDatatable.Rows.Count > 1)
            {
                try
                {
                    if (con.State == ConnectionState.Closed)
                        con.Open();
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy
                    (
                    con,
                    SqlBulkCopyOptions.TableLock |
                    SqlBulkCopyOptions.FireTriggers |
                    SqlBulkCopyOptions.UseInternalTransaction,
                    null
                    ))
                    {                       
                       
                             bulkCopy.DestinationTableName = TABLENAME;
                       
                        bulkCopy.NotifyAfter = 1000;
                        
                        for (int i = 0; i <= ExcelDatatable.Columns.Count - 1; i++)
                        {
                            string colname = ExcelDatatable.Columns[i].ColumnName.ToString();
                           bulkCopy.ColumnMappings.Add(ExcelDatatable.Columns[i].ColumnName.ToString(), colname);
                        }

                        bulkCopy.WriteToServer(ExcelDatatable);
                    }
                    con.Close();
                }
                catch (Exception ee)
                {

                }
            }
        }
 
Share this answer
 
v2
Comments
Gujula Ravindra Reddy 21-Sep-12 6:46am    
thanklu where we can write the above code..?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900