Using .Net 4.0 and reading Excel files, I had a similar problem with the OleDbDataAdapter - that is, reading in a mixed data type in the "PartID" column in MS Excel, where the PartID value can be numeric (for example, 561) or text (for example, HL4354 ), although the Excel column has been formatted as "Text."
From what I can tell, ADO.NET selects the data type based on most of the values in the column (with reference to the numeric data type). that is, if most of the PartID in the sample set is numeric, ADO.NET will declare the column numeric. Therefore, ADO.Net will try to assign each cell to a number that will not be executed for the “text” PartID values and will not import these “text” PartIDs.
My solution was to set the OleDbConnection connectionstring to use Extended Properties=IMEX=1;HDR=NO to indicate that it is an import and that the tables (tables) will not contain headers. The excel file has a header line, so in this case, tell ado.net not to use it. Then, in the code, remove this header row from the dataset, and you have a mixed data type for this column.
string sql = "SELECT F1, F2, F3, F4, F5 FROM [sheet1$] WHERE F1 IS NOT NULL"; OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PrmPathExcelFile + @";Extended Properties=""Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text"""); OleDbCommand cmd = new OleDbCommand(sql, connection); OleDbDataAdapter da = new OleDbDataAdapter(cmd); DataSet ds = new DataSet(); ds.Tables.Add("xlsImport", "Excel"); da.Fill(ds, "xlsImport");
// now you can use LINQ to search for fields
var data = ds.Tables["xlsImport"].AsEnumerable(); var query = data.Where(x => x.Field<string>("LocationID") == "COOKCOUNTY").Select(x => new Contact { LocationID= x.Field<string>("LocationID"), PartID = x.Field<string>("PartID"), Quantity = x.Field<string>("Qty"), Notes = x.Field<string>("UserNotes"), UserID = x.Field<string>("UserID") });
Brian Wells Apr 19 '11 at 19:20 2011-04-19 19:20
source share