We have two situations:
1. Columns have no name.
In this case we have to specify it in the property HDR HDR = NO
if (Path.GetExtension(pathArchivo).ToUpper() == ".XLSX")
{
cb.Provider = "Microsoft.ACE.OLEDB.12.0";
cb.Add("Extended Properties", "Excel 12.0 Xml;HDR=NO;IMEX=1;");
}
And we refer to the columns as F1, F2, Fn, etc. according to what we need, for example, if we only need columns A (F1) and C (F3):
OleDbConnectionStringBuilder cb = new OleDbConnectionStringBuilder();
cb.DataSource = pathArchivo;
if (Path.GetExtension(pathArchivo).ToUpper() == ".XLS")
{
cb.Provider = "Microsoft.Jet.OLEDB.4.0";
cb.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX=1;");
}
else if (Path.GetExtension(pathArchivo).ToUpper() == ".XLSX")
{
cb.Provider = "Microsoft.ACE.OLEDB.12.0";
cb.Add("Extended Properties", "Excel 12.0 Xml;HDR=NO;IMEX=1;");
}
OleDbConnection conexionOleDb = new OleDbConnection(cb.ConnectionString);
conexionOleDb.Open();
OleDbCommand cmd = conexionOleDb.CreateCommand();
cmd.CommandText = "SELECT F1,"
+ "F3 "
+ "FROM [Sheet1$]";
OleDbDataReader dr = cmd.ExecuteReader();
2. The columns do have a name
We place the property HDR = YES
and specify the name of our columns, for example, column A is called NAME and column C is called LAST NAME:
OleDbConnectionStringBuilder cb = new OleDbConnectionStringBuilder();
cb.DataSource = pathArchivo;
if (Path.GetExtension(pathArchivo).ToUpper() == ".XLS")
{
cb.Provider = "Microsoft.Jet.OLEDB.4.0";
cb.Add("Extended Properties", "Excel 8.0;HDR=YES;IMEX=1;");
}
else if (Path.GetExtension(pathArchivo).ToUpper() == ".XLSX")
{
cb.Provider = "Microsoft.ACE.OLEDB.12.0";
cb.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES;IMEX=1;");
}
OleDbConnection conexionOleDb = new OleDbConnection(cb.ConnectionString);
conexionOleDb.Open();
OleDbCommand cmd = conexionOleDb.CreateCommand();
cmd.CommandText = "SELECT NOMBRE,"
+ "APELLIDO "
+ "FROM [Sheet1$]";
OleDbDataReader dr = cmd.ExecuteReader();