gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:30:14 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com