I have a C# program that is supposed to pull data from a small, four-column spreadsheet (.xlsx). It reads the first column fine, however when it gets to the second I get the following error:
“Specified cast is not valid”
I’ve checked and re-checked the format of the cells, and there is no difference between the first column, which reads just fine, and the second. Below are the values for the first row in the spreadsheet. Each value represents one separate column.
121220 330004 Dual 02/22/2012
And here is the code that I am using. the Id variable loads just fine, it is the courseCode which is causing the problem.
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=C:\Projects\sym_AgentServices_INT\Book1.xlsx;"
+ "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [CE$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
string Id = "";
string courseCode = "";
string partner = "";
string effectiveDate = "";
string expirationDate = "";
Id = reader.GetString(0);
courseCode = reader.GetString(1);
partner = reader.GetString(2);
effectiveDate = reader.GetString(3);
expirationDate = reader.GetString(4);
}
}
}
EDIT
I’ve analyzed the reader object at runtime and found the following: by expanding base a number of times and opening up the _bindings property of System.Data.OleDb.OleDbDataReader I found that there was only one entry in there (“0”). However, if I open 0 up, then expand the _columnBindings property I find the values 0 – 4.
Could my syntax be incorrect when extracting data from the reader (“reader.GetString(x)”)?
FINAL EDIT
Instead of using .GetString(x) I would highly recommend simply using reader[x].ToString(). This solved the problem.
When I use reader[n].ToString(), the error goes away for me:
Here’s my test data set…