C# SQL Server 字符串在检索期间转换为 Int

标签 c# sql-server

我有以下 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/

相关文章:

sql-server - 了解 SQL Server 加密(通过密码)?

sql-server - SQL Server : If @variable is null set @variable = x

c# - 为什么使用此代码在运行时得到 "Invalid args"?

sql - SUM 两个 CASE 函数

c# - 用于 C# 静态字典的 VS 2008 Intellisense

c# - 更新数组mongodb c#驱动程序中的字段

SQL Server 按替代分组而不丢失行

c# - 如何使用 Entity Framework 更新数据库而无需迁移历史记录

c# - 非常慢的性能结构

c# - Entity Framework 代码优先 6.0 : is there any annotations to add index to a column(s)