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);
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top