简体   繁体   中英

Delete empty rows in a Dataset

How do I delete the empty rows in my dataset?

I am reading data from an excel spreadsheet that has a few empty rows at the bottom.

Here is my code so far:

ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", VariableFile);

OleDbConnection objConn = new OleDbConnection(ConnectionString);

objConn.Open();

OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Requirements$]", objConn);

OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

objAdapter1.SelectCommand = objCmdSelect;

DataSet objDataset1 = new DataSet();

objAdapter1.Fill(objDataset1);

objConn.Close();

为什么不修改查询以仅提取非空数据呢?

Every solution I have found told me to modify the Excel query like you have it. So that isn't much help. You could just create a DataView from your Table that would look at the non-blank rows. Do you know what the columns are beforehand? Even if you don't you could still loop over the column names and build a filter string for the DataView.

string filter = "";

foreach (DataColumn dc in dt.Columns)
{
    filter += dc.ColumnName + " <> '' ";

    if (dt.Columns[dt.Columns.Count-1].ColumnName != dc.ColumnName)
    {
        filter += " AND ";
    }
}

DataView view = new DataView(dt);
view.RowFilter = filter;
dt = view.ToTable();

Use Linq to include only rows that have a non-null/blank value in any of its columns.

var filteredData = sourceDataTable.AsEnumerable()
         .Where(row => row.ItemArray.Any(col => !String.IsNullOrWhiteSpace(col.ToString())))
         .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM