【发布时间】:2021-10-18 06:43:21
【问题描述】:
我正在尝试从 Excel 中读取数据并使用 OpenXML 将其存储到 DataTable 中。我希望 DataTable 中的数据与 Excel 工作表中的数据一样,但是当 Excel 中有一个空单元格时,它看起来并不像预期的那样。
因为代码row.Descendants<Cell>().ElementAt(i) 在读取数据时会跳过空单元格,并且在 DataTable 中的行和列存储不正确。我使用下面的代码解决了这个问题,但是当我的 excel 有超过 26 列时,它不能按预期工作,并且数据再次错误地存储在 DataTable 中。
(即,从 AA、AB、AC 列读取数据时)
当列数超过 26 列时,谁能帮我重写这段代码来处理这个问题。
private static int CellReferenceToIndex(Cell cell)
{
int index = 0;
string reference = cell.CellReference.ToString().ToUpper();
foreach (char ch in reference)
{
if (Char.IsLetter(ch))
{
int value = (int)ch - (int)'A';
index = (index == 0) ? value : ((index + 1) * 26) + value;
}
else
{
return index;
}
}
return index;
}
【问题讨论】:
-
@Jazb - 我尝试了这个答案,但是当整列为空时,它无法正常工作。例如,在excel中,如果AB列是空的,当它读取AC时,它正在跳过B列中的值。我想说的是,如果单元格为空,但如果整个列本身为空,则该解决方案无法按预期工作。