2017-02-26 83 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

相关问题