[英]Get the Column Index of a Cell in Excel using OpenXML C#
我一直在环顾四周,似乎无法找到如何做到这一点。 我有一张 excel 表,我正在使用 OpenXML 阅读它。 现在正常的做法是遍历行,然后遍历单元格以获取值,这很好。 但是除了值之外,我还需要单元格的位置,格式为(rowindex,ColumnIndex)。 我设法获得了rowIndex,但似乎无法弄清楚获得列索引。
我实际上认为这很容易,但显然不是。
这比您想象的要复杂一些,因为架构允许省略空单元格。
要获取索引,您可以使用具有CellReference
属性的Cell
对象,该属性以A1
、 B1
等格式提供引用。您可以使用该引用来提取列号。
您可能知道,在 Excel A = 1
、 B = 2
等直到Z = 26
时,单元格以A
为前缀以给出AA = 27
、 AB = 28
等。请注意,在AA
的情况下,第A
值为秒的 26 倍; 即它“价值”26,而第二个A
“价值”1,总共27。
要计算列索引,您可以反转字母,然后取第一个字母的值并将其添加到运行总数中。 然后将第二个字母的值乘以 26,将总数与第一个数字相加。 对于第三个,您将其乘以 26 两次并相加,对于第四个,将其乘以 26 3 次,依此类推。
因此,对于ABC
列,您将执行以下操作:
C = 3
B = 2 * 26 = 52
A = 1 * 26 *26 = 676
3 + 52 + 676 = 731
在 C# 中,以下将起作用:
private static int? GetColumnIndex(string cellReference)
{
if (string.IsNullOrEmpty(cellReference))
{
return null;
}
//remove digits
string columnReference = Regex.Replace(cellReference.ToUpper(), @"[\d]", string.Empty);
int columnNumber = -1;
int mulitplier = 1;
//working from the end of the letters take the ASCII code less 64 (so A = 1, B =2...etc)
//then multiply that number by our multiplier (which starts at 1)
//multiply our multiplier by 26 as there are 26 letters
foreach (char c in columnReference.ToCharArray().Reverse())
{
columnNumber += mulitplier * ((int)c - 64);
mulitplier = mulitplier * 26;
}
//the result is zero based so return columnnumber + 1 for a 1 based answer
//this will match Excel's COLUMN function
return columnNumber + 1;
}
请注意, CellReference
也不能保证在 XML 中(尽管我从未见过它不在那里)。 在CellReference
为空的情况下,单元格被放置在最左边的可用单元格中。 RowIndex
在规范中也不是强制性的,因此它也可以省略,在这种情况下,单元格放置在可用的最高行中。 更多信息可以在这个问题中看到。 在CellReference
为null
情况下, CellReference
的答案是正确的方法。
小就是美
int ColumnIndex(string reference)
{
int ci=0;
reference=reference.ToUpper();
for (int ix = 0; ix < reference.Length && reference[ix] >= 'A';ix++ )
ci = (ci * 26) + ((int)reference[ix] - 64);
return ci;
}
[TestCase( 1, 0, "A1" )]
[TestCase( 2, 25, "Z2" )]
[TestCase( 2, 38, "AM2" )]
[TestCase( 2, (26 * 4) + 1, "DB2" )]
[TestCase( 2, (26 * 26 * 26 * 18) + (26 * 26 * 1) + (26 * 26 * 1) + ( 26 * 1 ) + 2, "RBAC2" )]
public void CanGetCorrectCellReference( int row, int column, string expected )
=> GetCellReference( (uint)row, (uint)column ).Value.ShouldEqual( expected );
public static StringValue GetCellReference( uint row, uint column ) =>
new StringValue($"{GetColumnName("",column)}{row}");
static string GetColumnName( string prefix, uint column ) =>
column < 26 ? $"{prefix}{(char)( 65 + column)}" :
GetColumnName( GetColumnName( prefix, ( column - column % 26 ) / 26 - 1 ), column % 26 );
Row row = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>().FirstOrDefault();
var totalnumberOfColumns = 0;
if (row != null)
{
var spans = row.Spans != null ? row.Spans.InnerText : "";
if (spans != String.Empty)
{
//spans.Split(':')[1];
string[] columns = spans.Split(':');
startcolumnInuse = int.Parse(columns[0]);
endColumnInUse = int.Parse(columns[1]);
totalnumberOfColumns = int.Parse(columns[1]);
}
}
在我的场景中,我只需要处理列名(没有单元格编号),并使用了 LINQ,认为值得放在这里以供参考。
const int AsciiTrim = 'A' - 1; //64
const int LastChar = 'Z' - AsciiTrim; //26
var colIndex = columnName
.Reverse()
.Select(ch => ch - AsciiTrim)
.Select((ch, i) => ch * Math.Pow(LastChar, i))
.Sum()
- 1; //make zero-index based
要恢复原状,以及完整的代码和测试,请参阅此要点。
在@petelids 答案中稍微修改了GetColumnIndex函数。 结果将是从零开始的索引。 如果需要为基于 1 的索引添加 1。
private static int CellReferenceToIndex(string reference)
{
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;
}
public static void CellReferenceToIndex(string reference, out int row_index, out int col_index)
{
row_index = 0;
col_index = 0;
foreach(char c in reference)
{
if (c >= '0' && c <= '9')
{
row_index = row_index * 10 + (c - '0');
}
if (c >= 'A' && c <= 'Z')
{
col_index = col_index * ('Z' - 'A' + 1) + (c - 'A' + 1);
}
}
}
private double CellReferenceToIndex(Cell cell)
{
// if Cell is ABC4 => position is
// = [Aindx * (26^2)] + [BIndx * (27^1)] + [CIndx * (27^0)]
// = [1 * (26^2)] + [2 * (27^1)] + [3 * (27^0)]
double index = 0;
char [] reference = cell.CellReference.ToString().ToUpper().Reverse().ToArray();
int letterPosition = 0;
foreach (char ch in reference)
{
if (char.IsLetter(ch))
{
int value = (ch - 'A') + 1; // so A is 1 not 0
index += value * Math.Pow(26, letterPosition++);
}
}
return index;
}
只是为了为这个老问题添加一种新方法,我使用它作为一种快速方法来获取一行中单元格的列索引(假设您正在循环通过 SheetData 中的一行中的单元格,因为 OP 表明它们是)。
您可以使用 ElementsBefore 枚举来计算您当前循环的单元格之前的单元格,并且由于该 Count 是从一开始的,而 Element IEnumerables 是从零开始的,因此使用 Count 将为您提供单元格的列索引。当前重新打开(本质上,ElementsBefore + 1 = 当前单元格的列索引)。
所以,像这样的事情......
For Each r In sht.Elements(Of Row)
For Each c In sht.Elements(Of Row).ElementAt(r.RowIndex).Elements(Of Cell)
Dim iColumnIndex = c.ElementsBefore.Count
Next
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.