简体   繁体   English

在C#中从Excel文件格式化时间字段

[英]Formating time field from excel file in C#

I need to format the time value i get from an excel file to a string and then insert it into a sql table. 我需要将从Excel文件中获取的时间值格式化为字符串,然后将其插入sql表中。 I have used this code: 我使用了以下代码:

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

This worked only for the dtTruck field first time i executed the project. 第一次执行项目时,这仅对dtTruck字段有效。 So this is not formating the value at all. 因此,这根本不格式化值。 It inserts the time value as a string into my sql table as this 0,29166666667 instead of this 07:00 它将时间值作为字符串插入到我的sql表中,就像这个0,29166666667而不是这个07:00

My code: 我的代码:

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);
        }
    }
}

Can anyone help me with this ? 谁能帮我这个 ?

did you try this : 您是否尝试过这个:

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

Reference : 参考:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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