我有以下 C# 代码来从 SQL Server 数据库中检索一堆文字字符串。该表包含多个列,其中混合了一个和两个字符长度的代码,例如“AT”、“01”、“BC”。列数据类型为 VARCHAR,代码表为 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++;
}
最佳答案
添加这一行:
codeSheets.Cells[1, colIndex].NumberFormat = "@"; // cell as a text
或在此之前将您的列格式化为文本,如下所示:Format an Excel column (or cell) as Text in C#?
关于C# SQL Server 字符串在检索期间转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42472097/