我有同样的问题。但不同之处在于我的空行位于中间,我有超过50列。用户想要查看重复的行,这意味着我无法使用SELECT DISTINCT * FROM [excel]
空行可以在任何地方。到目前为止,我面临的最大优势超过100,000行。
是否有更有效的方法来删除空行,或者我必须循环并检查每一行中的所有列?
void SelectDataFromExcel()
{
string connectionString = ConfigurationSettings.AppSettings["ExcelConn"].ToString();
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
OleDbCommand dbCommand;
OleDbDataAdapter dataAdapter;
foreach (var sheet in Sheets)
{
dbCommand = new OleDbCommand("select DISTINCT* From[" + sheet + "$]", excelConnection);
System.Threading.Thread.Sleep(1000);
this.Invoke((MethodInvoker)delegate
{
listBox1.Items.Add("Tablo ismi: " + sheet.ToUpper(CultureInfo.InvariantCulture) + " Tablo Satır Sayısı: "+ dSet.Tables[sheet].Rows[0][0].ToString());
});
dataAdapter = new OleDbDataAdapter(dbCommand);
dTable = new DataTable();
dataAdapter.Fill(dTable);
dTable.TableName = sheet.ToUpper(CultureInfo.InvariantCulture);;
ArrangedDataList(dTable);
FillSqlTable(dTable, dTable.TableName);
dTable.Dispose();
dataAdapter.Dispose();
dbCommand.Dispose();
}
excelConnection.Close();
excelConnection.Dispose();
t1.Abort();
}
答案 0 :(得分:6)
修改强>
这将删除每个列中没有任何内容或空格的所有行:
dataTable = dataTable.Rows.Cast<DataRow>().
Where(row => !row.ItemArray.All(field => field is System.DBNull ||
string.Compare((field as string).Trim(), string.Empty) ==
0)).CopyToDataTable();
<强>预强>
实现目标的一种方法是检查空值
DataView dv = null;
dv = new DataView();
{
dv.Table = myDatatable;
dv.AllowDelete = true;
dv.AllowEdit = true;
dv.AllowNew = true;
dv.RowFilter = "myField = ' '";
}
答案 1 :(得分:1)
试试这个
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
if (dt.Rows[i][0].ToString() == String.Empty )
{
dt.Rows.RemoveAt(i);
}
}
答案 2 :(得分:1)
这对我也有用。
DataTable dt = table.Rows.Cast<DataRow>().Where(r => string.Join("", r.ItemArray).Trim() != string.Empty).CopyToDataTable();