【问题标题】:C# - Using OpenXML how to read blank spaces on excel filesC# - 使用 OpenXML 如何读取 excel 文件上的空格
【发布时间】:2012-03-19 14:34:34
【问题描述】:

我正在寻找一些解决方案,但没有找到,目前我在使用 OpenXML 读取 excel 文件时遇到问题。对于完美的数据,不会有任何问题,但对于带有空格的数据,列似乎向左移动,产生一个错误,指出索引不正确,因为它实际上向左移动。我找到了一个解决方案,您可以将其放置在中间的单元格中,但是当我尝试它时,出现一个错误,指出在使用此代码读取某个单元格时未将对象引用设置为对象的实例(来源来自中的答案这里用于插入单元格How do I have Open XML spreadsheet "uncollapse" cells in a spreadsheet?)

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;
    }
}

还有什么其他方法可以让我在不将数据向左移动的情况下将空白单元格读取为空白?

所有帮助将不胜感激! :)

谢谢!

【问题讨论】:

    标签: c# openxml


    【解决方案1】:

    在 Open XML 中,xml 文件不包含空白单元格的条目,这就是跳过空白单元格的原因。我遇到了同样的问题。唯一的解决方案是应用一些逻辑。

    例如:

    当我们读取一个单元格时,我们可以通过以下代码获取其列名(A、B、C 等)

    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 循环到 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 的唯一方法。在阅读过程中添加空白单元格是浪费时间。您可以根据自己添加更多逻辑
    试试这个。这肯定会奏效。或者如果您找到更好的解决方案,请告诉我 祝你有美好的一天:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      相关资源
      最近更新 更多