如何防止OleDbDataReader.ExecuteReader从自动追加整数到重复列值

本文关键字:整数 追加 OleDbDataReader 何防止 ExecuteReader | 更新日期: 2023-09-27 18:06:58

我试图从Excel (xls)电子表格导入数据。我需要抛出一个错误,如果重复的值出现在标题行。我使用OleDbDataReader来摄取工作表数据。我遇到的问题是。net在重复列的末尾附加了一个唯一的整数,以便所有的值都是唯一的。

头值在运行时将是未知的。如果发现重复的头值,应该停止对文件的处理。

例如,一个标题如下的电子表格:品牌,型号,年份,品牌将显示为:品牌,型号,年份,制造

下面是一些代码:
           string selectString = "Select * from $Sheet1";
           xlConnection = new OleDbConnection(connectionString);
           OleDbCommand cmd = new OleDbCommand(selectString, xlConnection); 
           OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                for (int fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++)
                {
                    string columnValue = reader.GetName(fieldIndex);
                }
            }

GetName返回Make, Model, Year, Make1

是否有办法防止这种行为?

如何防止OleDbDataReader.ExecuteReader从自动追加整数到重复列值

考虑使用:

  string selectString = "Select Make, Model, Year from $Sheet1";

代替:

  string selectString = "Select * from $Sheet1";

我有同样的需求,也面临同样的挑战。

我通过修改连接字符串来设置HDR=NO来解决这个问题。然后选择第一行并循环遍历每列中的值以检查惟一性。如果我找到一个匹配,我抛出DuplicatNameException与DataTable一致。