2017-02-26 45 views
2

我有以下c#代碼從SQL Server數據庫中檢索一串文字字符串。該表包含若干列,其中包含一個和兩個字符長度的代碼組合,例如「AT」,「01」,「BC」。列數據類型是VARCHAR,而數據表是Microsoft.Office.Interop.Excel._Worksheet。C#SQL Server字符串在檢索期間被轉換爲Int

問題是,當我得到「01」作爲查詢結果時,Excel工作表顯示1而不是01。當我在桌子上進一步分析時,這會導致問題。我懷疑在檢索期間,01以某種方式被轉換爲整數而不是字符串。有人能指出爲什麼會發生這種情況嗎

sqlString = "SELECT DISTINCT(BUSCODES) AS COLCODES FROM ANALYSISTABLE"; 
SqlCommand codeRetrieval = new SqlCommand(sqlString, dbConn); 
codeRetrieval.CommandTimeout = 0; 
SqlDataReader codeReader = codeRetrieval.ExecuteReader(); 


while (codeReader.Read()) 
{ 
    if (codeReader["COLCODE"] == DBNull.Value) 
     codeSheets.Cells[1, colIndex] = "NULL"; 
    else if (string.Compare(codeReader["COLCODE"].ToString(), "") == 0) 
     codeSheets.Cells[1, colIndex] = "Empty String"; 
    else if (string.Compare(codeReader["COLCODE"].ToString(), " ") == 0) 
     codeSheets.Cells[1, colIndex] = "Single Space"; 
    else if (string.Compare(codeReader["COLCODE"].ToString(), " ") == 0) 
     codeSheets.Cells[1, colIndex] = "Double Space"; 
    else 
     codeSheets.Cells[1, colIndex] = codeReader["COLCODE"].ToString(); 

    colIndex++; 
} 
+0

你確定這是不是被格式化爲一個Excel單元格一個號碼? – spender

+0

您需要將單元格格式化爲文本。 http://stackoverflow.com/questions/2067926/format-an-excel-column-or-cell-as-text-in-c – SqlZim

+0

謝謝大家的意見,我從來沒有想過Excel自動格式化它。我假設如果我存儲一個字符串類型,它將是Excel中的字符串類型。但我想我是錯的,哈哈。 –

回答

1

加入這一行:

codeSheets.Cells[1, colIndex].NumberFormat = "@"; // cell as a text 

或在此之前設置列的格式文本,在這裏看到:Format an Excel column (or cell) as Text in C#?

+0

非常感謝,我從來沒有認爲這將是Excel的一個問題。 –

+0

@BrianWang高興地幫忙! – SqlZim