I have a need to read in some client data from an Excel sheet. I found it very quick and easy to read the *.xls as data, this way:
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcelFile.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
using (var conn = new System.Data.OleDb.OleDbConnection(connString)) {
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * From [SheetName$]", conn);
OleDbDataReader reader = cmd.ExecuteReader();
int firstNameOrdinal = reader.GetOrdinal("First Name");
int lastNameOrdinal = reader.GetOrdinal("Last Name");
while (reader.Read()) {
Console.WriteLine("First Name: {0}, Last Name: {1}",
reader.GetString(firstNameOrdinal),
reader.GetString(lastNameOrdinal));
}
}
The problem comes in at the 4th line: SELECT * FROM [SheetName$]. In this example, you need to replace "SheetName" with the name of the worksheet you are trying to read. Most of the time, the client names this the same, and all is fine.
But sometimes they don’t, and that means some manual work on our part to fix it. There is always just one sheet (in this case anyway) and so I’d rather just tell the code to “use the first sheet, whatever it is named”.
I haven’t been able to find a way to accomplish this using this technique, so I’m reaching out to the community. Thanks in advance for any advice.
PS – We have to go through a length approval process for external files (e.g. FileHelpers) and I prefer using this process because it does not require a third-party library. I’d prefer to limit answers to this method if possible.
Thanks.
The answer here might suit your needs:
http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/711cf5f9-75fc-4a02-9a96-08aec48dad69/
It uses
.GetOleDbSchemaTable()to get a list of sheet names in a workbook.