这是有道理的,因为Excel不会存储空单元格的值。如果您使用Open XML SDK 2.0 Productivity Tool打开文件并遍历XML到单元格级别,您将看到只有包含数据的单元格才会出现在该文件中。
您可以选择在要遍历的单元格范围内插入空白数据,或编程式地找出被跳过的单元格并相应地调整索引。
我创建了一个示例Excel文档,在单元格引用A1和C1中放置了一个字符串。然后我在Open XML Productivity Tool中打开了Excel文档,以下是存储的XML:
<x:row r="1" spans="1:3"
xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:c r="A1" t="s">
<x:v>0</x:v>
</x:c>
<x:c r="C1" t="s">
<x:v>1</x:v>
</x:c>
</x:row>
在这里,您将看到数据对应于第一行,并且仅为该行保存了两个单元格的数据。保存的数据对应于A1和C1,并且没有保存任何空值单元格。
要获取所需的功能,您可以像上面那样遍历单元格,但需要检查单元格引用的值并确定是否跳过了任何单元格。为此,您需要两个实用程序函数,以从单元格引用中获取列名,然后将该列名转换为基于零的索引:
private static List<char> Letters = new List<char>() { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ' };
public static string GetColumnName(string cellReference)
{
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellReference);
return match.Value;
}
public static int? GetColumnIndexFromName(string columnName)
{
int? columnIndex = null;
string[] colLetters = Regex.Split(columnName, "([A-Z]+)");
colLetters = colLetters.Where(s => !string.IsNullOrEmpty(s)).ToArray();
if (colLetters.Count() <= 2)
{
int index = 0;
foreach (string col in colLetters)
{
List<char> col1 = colLetters.ElementAt(index).ToCharArray().ToList();
int? indexValue = Letters.IndexOf(col1.ElementAt(index));
if (indexValue != -1)
{
if (index == 0 && colLetters.Count() == 2)
{
columnIndex = columnIndex == null ? (indexValue + 1) * 26 : columnIndex + ((indexValue + 1) * 26);
}
else
{
columnIndex = columnIndex == null ? indexValue : columnIndex + indexValue;
}
}
index++;
}
}
return columnIndex;
}
然后您可以迭代单元格并检查单元格引用与列索引的比较。 如果它小于,则将空数据添加到tempRow中,否则只需读取单元格中包含的值。 (注意:我没有测试下面的代码,但一般思路应该是有帮助的):
DataRow tempRow = dt.NewRow();
int columnIndex = 0;
foreach (Cell cell in row.Descendants<Cell>())
{
int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));
if (columnIndex < cellColumnIndex)
{
do
{
tempRow[columnIndex] =
columnIndex++;
}
while(columnIndex < cellColumnIndex);
}
tempRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);
if (tempRow[i].ToString().IndexOf("Latency issues in") > -1)
{
Console.Write(tempRow[i].ToString());
}
columnIndex++;
}