1

我需要将我从 excel 文件中获得的时间值格式化为字符串,然后将其插入到 sql 表中。我用过这段代码:

dtTruck = string.Format(dtTruck, "Long Time");
dtPlane = string.Format(dtPlane, "Long Time");

这仅适用于我第一次执行项目时的 dtTruck 领域。所以这根本没有形成价值。它将时间值作为字符串插入到我的 sql 表中,作为0,29166666667而不是07:00

我的代码:

public void ReadExcelFile()
{
    string filename = @"C:\Temp\Copy2.xlsx";
    using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""))
    {
        try
        {
            connection.Open();
            string sqlCmd1 = "SELECT  * FROM [Sheet1$]";
            using (OleDbCommand command = new OleDbCommand(sqlCmd1, connection))
            {
                command.CommandType = System.Data.CommandType.Text;
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        alias = "" + reader[3];
                        codeT = "" + reader[4];
                        dtTruck = "" + reader[5];
                        codeP = "" + reader[6];
                        dtPlane = "" + reader[7];
                        dtDealer = "" + reader[8];

                        dtTruck = string.Format(dtTruck, "Long Time");
                        dtPlane = string.Format(dtPlane, "Long Time");

                        SearchForAdrIDAndCustID(Convert.ToString(reader[0]), Convert.ToString(reader[3]));
                        InsertData(custID, "" + reader[3], adrID, dtTruck, codeT, dtPlane, codeP, dtDealer);
                    }
                }
            }

        }
        catch (Exception exception)
        {
            Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
        }
    }
}

谁能帮我这个 ?

4

1 回答 1

0

你试过这个吗:

dtTruck = string.Format(dtTruck,"{0:T}"); 

参考 :

http://www.csharp-examples.net/string-format-datetime

于 2012-11-19T10:27:43.033 回答