【问题标题】:How to select number from Excel file?如何从 Excel 文件中选择数字?
【发布时间】:2011-04-18 15:26:09
【问题描述】:

我使用此代码将 Excel 文件加载到数据表中:

 public static DataTable ImportExcelFile(string connectionString)
        {
            DbProviderFactory factory =
                DbProviderFactories.GetFactory("System.Data.OleDb");
            var listCustomers = new DataTable();

            using (DbConnection connection = factory.CreateConnection())
            {
                if (connection != null)
                {
                    connection.ConnectionString = connectionString;
                    using (DbCommand command = connection.CreateCommand())
                    {
                        // Cities$ comes from the name of the worksheet
                        command.CommandText = "SELECT * FROM [Sheet1_2$]";
                        connection.Open();
                        using (DbDataReader dr = command.ExecuteReader())
                        {
                            listCustomers.Load(dr);
                        }
                    }
                }
            }
            return listCustomers;
        }

问题是,Excel 文件中的某些列,例如 AccountID,包含字符串数据 ('quanmv') 和数字 (123456)。当我使用此代码时,它只是忽略具有数值的单元格,并将其留空。

我该如何解决这个问题?

非常感谢。

【问题讨论】:

    标签: c# .net excel datatable oledb


    【解决方案1】:

    默认情况下,与 excel 的连接会尝试猜测列的数据类型。如果它猜错了,它可能会在类型不转换的地方留下空值。您可以在连接字符串中添加IMEX=1 以关闭此自动猜测,并将所有值视为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多