我有以下c#代码从SQL Server数据库中检索一堆文字字符串。该表包含多个列,其中包含一个和两个字符长度的代码,例如" AT"," 01"," BC"。列数据类型为VARCHAR,而codeheets为Microsoft.Office.Interop.Excel._Worksheet。
问题在于,当我得到" 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 :(得分:1)
添加以下行:
codeSheets.Cells[1, colIndex].NumberFormat = "@"; // cell as a text
或在此之前将列格式化为文本,如下所示:Format an Excel column (or cell) as Text in C#?