2011-02-17 41 views
9

我使用如下OLEDB連接導入excel表到數據表。如何僅使用C#中的oledb上載非空行的Excel電子表格?

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之前刪除了幾行內容時出現問題。它讀取那些空行以及非空行,並且由於違反業務規則(必填字段缺失)而將數據保存在數據庫中失敗。 我試過是把WHERE條件查詢:

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

因此,這將具有數據只選擇那些行。 但我不能夠比較非串場即日期,整型等,這些作爲正在添加DBNull的空當。 任何一個可以請建議這樣做的方式,我不想使用的DataReader。

回答

7

使用

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

感謝Ekkehard的回覆,但它不工作。 – 2011-02-17 08:13:45

+0

我的歉意,但它似乎你的方式也工作。 – 2011-02-17 09:03:36

+0

+1我在Excel中使用了這個。 – Fionnuala 2011-02-17 09:33:10

12

如何查詢已使用LINQ to對象執行濾波後的行:

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

擴大對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(); 
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 
相關問題