2011-10-10 20 views
1

我正在通過asp.net C#Web應用程序導入電子表格。在我將它傳遞給存儲過程之前,我需要驗證excel - >數據表結果的結果。如果枚舉每個所需列的所有行以驗證是否有值,那麼是否有人有更快的解決方案?驗證值存在於多個DataTable列中

實施Jame的建議;我最終做的是克隆只克隆模式的原始表。然後,我將AllowDBNull = false設置爲我想要的列。然後最後一步是在TryCatch語句中進行合併。如果合併失敗,你將得到一個必要的字段驗證錯誤拋出給用戶。

public DataTable UploadSpreadsheetData(string tempFile) 
    { 
     try 
     { 
      __filepath = tempFile; 
      this.onConnectionStringChanged(); 
      string _sheetname = GetSheetName(); 
      DataTable _importedData = ReadTable(_sheetname); 
      DataTable _newTableStructure = GetClone(_importedData); 
      MergeDataTables(_importedData, _newTableStructure); 
      return _newTableStructure; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      this.Connection.Close(); 
      this.Connection.Dispose(); 
      DeleteTempFile(tempFile); 
     } 
    } 

    private DataTable GetClone(DataTable table) 
    { 
     DataTable _cloneTable = table.Clone(); 
     _cloneTable.Columns["System Code"].AllowDBNull = false; 
     return _cloneTable; 
    } 

    private static void MergeDataTables(DataTable _importedData, 
     DataTable _newTableStructure) 
    { 
     try 
     { 
      _newTableStructure.Merge(_importedData, true, MissingSchemaAction.Add); 
     } 
     catch (Exception ex) 
     { 
      // Add a reference to required value structure for the 
      // end user to verify validity of the spreadsheet 
      throw new ApplicationException(String.Format("The following 
      error was encountered while importing the spreadsheet data. {0}. 
      Please check the spreadsheet to ensure all required values are 
      present.", ex.Message)); 
     } 
    } 
+1

更快的性能,我認爲(而不是更快(更容易)寫)? –

+0

是否需要確保值存在?或者爲了防止重複? –

+0

是高性能是主要目標,我需要的是我看到的字段 – Tim

回答

1

如果列被「失蹤」的值是nullDBNull.Value),你可以這樣做:

// or whatever means you use to get your table... 
DataTable dt = new DataTable(); 

// define your columns (whether imported or manual) 

// set the columns that must have a value to deny DBNull, for example if col 3 & 4: 
dt.Columns[3].AllowDBNull = false; 
dt.Columns[4].AllowDBNull = false; 

一旦這些列設置爲AllowDBNull = false那麼當你設置你會得到一個異常如果之前加載了數據,則將其加載到false,否則如果數據在設置爲false之後添加,您將在該行的Add上發生異常。

所以,如果可能的話,先設置你的列,但是如果在導入中定義了這些列,只需在try/catch中設置你的列爲AllowDBNull = false,如果你發現異常,你知道你有一個問題柱。

如果這些值是空白字符串,這當然不起作用。但如果這是你所需要的,我可以挖更多...

+0

這實際上是一個很好的建議。謝謝詹姆斯。更新到我的實施原始文章 – Tim

+0

@Tim:很好,很高興它幫助!如果您有任何其他問題,請告訴我... –