简体   繁体   中英

When Importing Sheet from Excel to SQL in C#, It Loses Time in DateTime columns

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#?

SQL server is probably not getting the full DateTime format correctly. I would log som lines of data here:

            while (dr.Read())
            {
                bulkCopy.WriteToServer(dr);
            }

... to investigate what format is actually attempted to be written.

I'm not too sure if this is of value or not, but using tsql datetime type, type contains milliseconds in this format:

WHERE OperationDate >= '2016-03-01 00:00:00.000'
and OperationDate NOT BETWEEN CONVERT(datetime,'2016-01-13') AND CONVERT(datetime,'2016-01-13 23:59:59:999')

Maybe some special handling in your reader?

I'm guessing that the data type is not correct on the SLQ Server side. Or...the data is not formatted correctly in Excel. Confirm that both are correct, and try something like what you see below.

string excelConnectionString = @"Provider=Microsoft 
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended 
Properties=""Excel 8.0;HDR=YES;"""; 
// Create Connection to Excel Workbook

We can Import excel to sql server like this

using (OleDbConnection connection = 
             new OleDbConnection(excelConnectionString)){

OleDbCommand command = new OleDbCommand 
            ("Select ID,Data FROM [Data$]", 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 = "ExcelData"; 
        bulkCopy.WriteToServer(dr); 
    } 

From here:

Import Excel file into Microsoft SQL Server using C#

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM