简体   繁体   中英

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).

Okay so my question is, is there a way to check if a column exist in specific excel sheet? 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.

If you can help me I'll be so grateful :)

OleDbConnection has GetOleDbSchemaTable command that allows you to retrieve just the list of columns. 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). You can then loop thru Rows collection examining "COLUMN_NAME" column, something like

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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