Like the title says, I am trying to write a program (and a general method that I can use for future programs) that will allow me to import all of the information from an Excel sheet into a table in SQL.
The method runs and all of the data will be in the SQL table, which has worked for everything I've needed it for up until this point. However, with a new report I need to run, I've found that this method loses the TIME in a DATETIME column in Excel.
For example, if a cell in Excel has the value of 7/26/2016 08:54:32, it will instead hold the value of 7/26/2016 00:00:00 in my SQL table. When I use the manual Import and Export Wizard that is included in the SQL Server Management Studio, it imports the datetime correctly and retains both values.
Here is the code for the method that I am using:
static bool ImportDataFromExcel(string excelFilePath, string excelSheet, string sqlTable)
{
//make sure the sheet name is correct
string myExcelDataQuery = "select * from [" + excelSheet + "]";
if (File.Exists(excelFilePath))
{
try
{
//create our connection strings
string sExcelConnectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=No;IMEX=1;'", excelFilePath);
string sSqlConnectionString = "Data Source=Server;Initial Catalog=Database;Integrated Security=true";
//execute query to erase data from destination table
string sClearSql = "delete from " + sqlTable;
SqlConnection sqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand sqlCMD = new SqlCommand(sClearSql, sqlConn);
sqlConn.Open();
sqlCMD.CommandTimeout = 80000;
sqlCMD.ExecuteNonQuery();
sqlConn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oleDbConn = new OleDbConnection(sExcelConnectionString);
OleDbCommand oleDbCmd = new OleDbCommand(myExcelDataQuery, oleDbConn);
oleDbConn.Open();
oleDbCmd.CommandTimeout = 60000;
OleDbDataReader dr = oleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.BulkCopyTimeout = 60000;
bulkCopy.DestinationTableName = sqlTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
dr.Close();
oleDbConn.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
return true;
}
Do any of you have any ideas of how to get this to work, or of another method to use for importing a table from Excel to SQL programmatically in C#?