2012-03-19 142 views
2

我正在尋找一些解決方案,但未能找到一個解決方案,目前我在使用OpenXML讀取excel文件時遇到問題。有了完美的數據,就不會有任何問題,但是帶有空白的數據,列似乎向左移動,產生一個錯誤,指出索引不正確,因爲它實際上移到了左邊。我發現了一個解決方案,您可以將它放置在單元格之間,但是當我嘗試它時,出現一個錯誤,指出在使用此代碼讀取某個單元格時未將對象引用設置爲對象的實例(源自答案這裏,用於插入細胞How do I have Open XML spreadsheet "uncollapse" cells in a spreadsheet?C# - 使用OpenXML如何讀取excel文件上的空格

public static string GetCellValue(SpreadsheetDocument document, Cell cell) 
{ 
    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart; 
    string value = cell.CellValue.InnerXml; 

    if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) 
    { 
     return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText; 
    } 
    else if (cell == null) 
    { 
     return null; 
    } 
    else 
    { 
     return value; 
    } 
} 

任何其他方式,其中可以閱讀,而不將數據移動到左側爲空白的空白單元格?

所有幫助將不勝感激! :)

謝謝!

回答

3

在Open XML中,xml文件不包含空白單元格的條目,這就是空白單元格被跳過的原因。我面臨同樣的問題。唯一的解決方案是應用一些邏輯。

例如:

當我們通過下面的代碼

string cellIndex = GetColumnName(objCurrentSrcCell.CellReference); 

其中

public static string GetColumnName(string cellReference) 
     { 
      // Create a regular expression to match the column name portion of the cell name. 
      Regex regex = new Regex("[A-Za-z]+"); 
      Match match = regex.Match(cellReference); 
      return match.Value; 
     } 
讀取小區我們可以得到其的ColumnName(A,B,C等)

您可以將這些單元格存儲在Hashtable中,其中的鍵可以是單元格ColumnName並且值可以是對象細胞的ct。和寫作從獲取哈希對象的細胞上連續一定基礎或你的邏輯就像...

你可以從一個循環到Z和閱讀特定的關鍵細胞像

if(objHashTable.Contains(yourKey)) 
{ 
    Cell objCell = (Cell) objHashTable[yourKey]; 
    //Insertcell or process cell 
} 
else 
{ 
    //do process for the empty cell like you may add a new blank cell 
    Cell objCell = new Cell(); 
    //Insert cell or process cell 
} 

這是當使用open xml的唯一方法。在閱讀期間添加空白單元是浪費時間。你可以根據你的添加更多的邏輯
試試這個。這肯定會起作用。或者如果你找到更好的解決方案,請告訴我 祝你有美好的一天:)