I have one Excel sheet with multiple tabs, need to insert this data into SQL Server using C#

asp.net c# sqlbulkcopy sql-server

Question

I have one Excel file which contains multiple sheets. Every sheet name is the same as a table name in SQL Server. I need to insert data of these Excel sheets into respective tables in database.

There are 13 tabs and 13 tables in SQL server DB.

I am able to insert one sheet's data to one table with the code below.

String strConnection = "Data Source=.;Initial Catalog=<>;Integrated Security=True";

String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);

// Create Connection to Excel work book 
OleDbConnection conn = new OleDbConnection(excelConnString);

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;

OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();

conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtSheet.Rows[0]["table_name"].ToString();
cmd.CommandText = "select * from [" + sheetName + "]";
da.SelectCommand = cmd;
da.Fill(dt);

using (OleDbDataReader dReader = cmd.ExecuteReader())
{
    using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
    {
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "TABLE NAME IN SQL";
        sqlBulk.WriteToServer(dReader);

        conn.Close();
    }
}

How can I insert the data from all the sheets?

1
0
12/8/2016 6:19:07 AM

Accepted Answer

The following should do it - you just need to iterate through each row in the tables table :

    ...
    DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    // iterate each sheet
    foreach (System.Data.DataRow sheet in dtSheet.Rows)
    {
        string sheetName = sheet["table_name"].ToString();
        cmd.CommandText = "select * from [" + sheetName + "]";
        da.SelectCommand = cmd;
        da.Fill(dt);

        using (OleDbDataReader dReader = cmd.ExecuteReader())
        {
            using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
            {
                // Give your Destination table name.  Table name is sheet name minus any $
                sqlBulk.DestinationTableName = sheetName.Replace("$", "");
                sqlBulk.WriteToServer(dReader);

                conn.Close();
            }
        }
    }
}
1
12/8/2016 4:39:00 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow