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?
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();
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.