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