2012-03-19 139 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的唯一方法。在阅读期间添加空白单元是浪费时间。你可以根据你的添加更多的逻辑
试试这个。这肯定会起作用。或者如果你找到更好的解决方案,请告诉我 祝你有美好的一天:)