C# - 使用 OpenXML 如何读取 Excel 文件上的空格

标签 c# openxml

我正在寻找一些解决方案,但没有找到,目前我在使用 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;
    }
}

还有其他方法可以将空白单元格读取为空白而不将数据移动到左侧吗?

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

谢谢!

最佳答案

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

例如:

当我们读取一个单元格时,我们可以通过以下代码获取它的ColumnName(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
}

这是使用开放 xml 的唯一方法。在读取过程中添加空白单元格是浪费时间。您可以根据自己的情况添加更多逻辑
尝试这个。这肯定会起作用。或者如果您找到更好的解决方案,请告诉我 祝你有美好的一天:)

关于C# - 使用 OpenXML 如何读取 Excel 文件上的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772096/

相关文章:

c# - HTTP 代码 405(不允许的方法),当我在 ASP.NET WebAPI CORS 中发送 POST 数据时

c# 锁定公共(public)方法和事件回调代码共享的对象

c# - 使用 Open XML SDK 将幻灯片从一个演示文稿复制到另一个

c# - 使用 OpenXML 将图片插入到 Word 文档的标题中

c# - NUnit 测试因 System.IO.FileNotFoundExeption 而失败

c# - 存储过程 DateTime 'Parameter not found in the collection' 错误

c# - 每当在aspx页面的文本框中键入内容时,我都想隐藏标签

.net - OpenXML 每行的文件越大越慢?

c# - OpenXml 强制图像适合父容器

xml - Excel with xml -> 标记和属性的来源和指南