Question

I'm importing excel into DataTable. The excel file contains 50x7 cells with data. The problem is that the Fill() method imports 368(?) rows regardless the fact that the data is in the first 50 of them. Any idea what might be the problem ?

I'm using OleDbDataAdapter for the import.

 connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
 string  commandString = "select * from [" + worksheetName + "]";
 OleDbDataAdapter adapter = new OleDbDataAdapter(commandString, connectionString);
 DataTable fileTable = new DataTable();
 adapter.Fill(fileTable);
Was it helpful?

Solution

Try this to remove empty cells from the DataTable:

adapter.Fill(fileTable);
fileTable = fileTable.AsEnumerable()
           .Where(row => !row.ItemArray.All(f => f is System.DBNull || String.IsNullOrWhiteSpace(f.ToString())))
           .CopyToDataTable();

Note that it also removes empty rows inside the sheet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top