简体   繁体   English

检查Excel工作表中是否存在列

[英]check if a column exists in Excel sheet

I've been working with a program where I import 2 excel files and those excel files have different columns names.. so it could be the possibility for a user to import the wrong excel file (with other column names) and my problem is that I'm reading the data from excel with OledbDataAdapter so I have to specified the name of each column, so when the user import the wrong file the program stop working (because the program can't find the right columns to get the data). 我一直在使用一个程序,我导入2个excel文件,那些excel文件有不同的列名...所以它可能是用户导入错误的excel文件(与其他列名称),我的问题是,我正在使用OledbDataAdapter从excel读取数据,所以我必须指定每列的名称,因此当用户导入错误的文件时程序停止工作(因为程序找不到正确的列来获取数据)。

Okay so my question is, is there a way to check if a column exist in specific excel sheet? 好的,我的问题是,有没有办法检查特定Excel工作表中是否存在列? So I'll be able to do something if the column doesn't exist in the file the user imported... 因此,如果用户导入的文件中不存在该列,我将能够执行某些操作...

Here's a part of my code: 这是我的代码的一部分:

OleDbCommand command1 = new OleDbCommand(
    @"SELECT DISTINCT serie FROM [Sheet1$] 
      WHERE serie =@MercEnInventario AND serie IS NOT NULL", connection);
command1.Parameters.Add(new OleDbParameter("MercEnInventario", MercInv));
string serieN = Convert.ToString(command1.ExecuteScalar());
readerOle = command1.ExecuteReader();
readerOle.Close();

I got an OleDbException when I try to give value to the string 'serieN' because the column name 'serie' doesn't exists in the excel file the user imported. 当我尝试为字符串'serieN'赋值时,我得到了OleDbException,因为用户导入的excel文件中不存在列名'serie'。

If you can help me I'll be so grateful :) 如果你能帮助我,我会非常感激:)

OleDbConnection has GetOleDbSchemaTable command that allows you to retrieve just the list of columns. OleDbConnection具有GetOleDbSchemaTable命令,允许您仅检索列列表。 An example code would be 一个示例代码将是

DataTable myColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, "Sheet1$", null });

This will return a DataTable, populated with column information (names, types and more). 这将返回一个DataTable,其中填充了列信息(名称,类型等)。 You can then loop thru Rows collection examining "COLUMN_NAME" column, something like 然后,您可以通过Rows集合循环检查“COLUMN_NAME”列,例如

foreach (DataRow dtRow in myColumns.Rows)
{
   if (dtRow["COLUMN_NAME"].ToString() == "serieN") // Do your stuff here ....
}

How about this: 这个怎么样:

public bool FieldExists(OleDbConnection connection, string tabName, string fieldName)
{
  var adapter = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", tabName), connection);
  var ds = new DataSet();
  adapter.Fill(ds, tabName);

  foreach (var item in ds.Tables[tabName].Rows[0].ItemArray)
  {
    if (item.ToString() == fieldName)
      return true;
  }
  return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM