2015-07-11 34 views
1

我想通過oledb連接使用以下代碼將當前時間插入到Excel中的Time列中,但是當我檢查Excel時,插入的值是Date格式。無法使用oledb更新excel中的當前時間使用oledb

值在Excel中更新 - 1/0/1900下午3時54分11秒

期望值 - 下午3時54分11秒

  string currentTime = DateTime.Now.ToString("hh:mm:ss.fff tt"); 
     string cmnd1 = "Create Table [" + currentDate + "] (TestCase char(100), ExecutionTime Time, Result char(20))"; 
     string cmnd2 = "Insert Into [" + currentDate + "] (TestCase, ExecutionTime, Result) values ("+ "'" + tName + "',@dd,'" + result +"')" ; 
     using (OleDbConnection conn = new OleDbConnection(ConnectionStringtd)) 
     { 
      OleDbCommand createSheet = new OleDbCommand(cmnd1, conn); 
      OleDbCommand insertResult = new OleDbCommand(cmnd2, conn); 
      insertResult.Parameters.AddWithValue("@dd", DateTime.Now.TimeOfDay); 
      conn.Open(); 
      try 
      { 
       createSheet.ExecuteNonQuery(); 
      } 
      catch(OleDbException) {} 
      insertResult.ExecuteNonQuery(); 
     } 

    } 
+0

'ExecutionTime'列的類型是什麼? –

+0

請勿使用AddWithValue。該方法自行推斷參數的類型,使用日期時間值很容易失敗。使用添加並指定OleDbType。嘗試各種選項。順便說一下,爲什麼只爲其他值使用一個參數和字符串concatantion? – Steve

+0

另外:空Try/Catch是一個錯誤。如果第一個命令失敗,第二個命令無法執行,但你不知道,因爲空捕獲吞噬了異常 – Steve

回答

0

AFAIK,當你進入使用輸入的時間部分將時間值存儲爲datetime,日期部分將自動從Excel中的the days before 1900 are incorrect開始自動爲1900年1月0日。

取而代之,將您的DateTime.Now直接傳遞給參數,並在格式單元格部分將您的列格式類型更改爲Time,格式爲h:mm:ss tt。順便說一下,你只是參考@dd部分。使用您嘗試插入的其他值的參數。不要連接它們。

insertResult.Parameters.AddWithValue("@dd", DateTime.Now); 

enter image description here

,不使用AddWithValue了。 It may generate unexpected and suprising results sometimes。使用Add方法重載指定您的參數類型及其大小。

還可以使用using語句像處理連接一樣處理您的命令。

+0

感謝您的寶貴意見。我 – Ash1994

+0

PFB更改的代碼。 – Ash1994

+0

string currentDate = DateTime.Now.ToString(「yyyyMMdd」); string currentTime = DateTime.Now.ToString(「h:mm:ss tt」); (TestCase char(100),ExecutionTime char(100),Result char(20))「; string cmnd2 =「Insert Into [」+ currentDate +「](TestCase,ExecutionTime,Result)values(@ tc,@ et,@ r)」; – Ash1994