如何在C#中使用oledb仅上传非空行的Excel电子表格?

时间:2011-02-17 07:02:34

标签: c# excel oledb spreadsheet

我使用oledb连接将Excel工作表导入DataTable,如下所示。

private static DataTable UploadExcelSheet(string fileName)
    {
        DataTable uploadDataTable;
        using (OleDbConnection objXConn = new OleDbConnection())
        {
            objXConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
                                            ";Extended Properties=\"Excel 12.0;IMEX=1\"";

            objXConn.Open();

            OleDbCommand objCommand =
                new OleDbCommand("SELECT * FROM Template$ ", objXConn);
            OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();

            // retrieve the Select command for the Spreadsheet
            objDataAdapter.SelectCommand = objCommand;

            // Create a DataSet
            DataSet objDataSet = new DataSet();

            // Populate the DataSet with the spreadsheet worksheet data
            objDataAdapter.Fill(objDataSet);
            uploadDataTable = objDataSet.Tables[0];
        }

        return uploadDataTable;
    }

一切都运行正常但是当用户在上传excel之前删除几行内容时会出现问题。它还会读取这些空行以及非空行,并且由于业务规则违规(缺少必填字段),因此在数据库中保存数据失败。 我尝试的是在查询中放置条件:

"SELECT * FROM  WHERE  not [CandidateId*] = 0 or not [Firstname*] = '' or not [Lastname] = '' or not [type*] = '' or not [DOB*] =" + DBNull.Value

因此它只会选择那些有数据的行。 但我无法比较非字符串字段,即Date,Integer等。当空时,它们将作为DBNull进行比较。 任何人都可以建议的方法,我不想使用DataReader。

4 个答案:

答案 0 :(得分:16)

扩展vc的答案,这将删除每个列包含任何内容或空格的所有行:

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();

答案 1 :(得分:12)

使用Linq对象执行查询后过滤行怎么样:

var filteredRows = uploadDataTable.Rows.Cast<DataRow>().Where(
  row => row.ItemArray.Any(field => !(field is System.DBNull)));

答案 2 :(得分:8)

使用

".. WHERE NOT ([Lastname] = '' OR [DOB*] IS NULL OR ... )

答案 3 :(得分:0)

扩展之前的答案,这对我有用。删除所有字段为空的行。

Dim deleteRows = From row In result.AsEnumerable
                 Where row.ItemArray.All(Function(field) Equals(field, DBNull.Value))

For Each deleteRow In deleteRows
    deleteRow.Delete()
Next