【发布时间】:2015-03-05 10:38:43
【问题描述】:
我已经四处寻找了一段时间,似乎无法找到如何做到这一点。 我有一个 Excel 表,我正在使用 OpenXML 阅读它。现在正常的事情是遍历行,然后遍历单元格以获取值,这很好。但除了值之外,我还需要单元格的位置,格式为(rowindex,ColumnIndex)。我设法获得了 rowIndex,但似乎无法弄清楚获得列索引。
我实际上认为这会很容易,但显然事实并非如此。
【问题讨论】:
我已经四处寻找了一段时间,似乎无法找到如何做到这一点。 我有一个 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 在规范中也不是强制性的,因此它也可以省略,在这种情况下,单元格被放置在可用的最高行中。更多信息请见this question。在CellReference 是null 的情况下,来自@BCdotWEB 的answer 是正确的方法。
【讨论】:
Z = 26*26 和A = 1*26*26。我在问,因为我正在尝试从单元格索引到单元格名称的相反操作。
Z 是“价值” 26。这将添加到第一个字母的值的 26 倍。例如。 ZZ 将是 (26 * 26) + 26 = 702。第三列中的A 是“值得”1。这将添加到第二个字母值的 26 倍和第一个字母值的 26 * 26 倍。例如 AAA 将是 (26 * 26 * 1) + (26 * 1) + 1 = 703。
小而美
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]);
}
}
【讨论】:
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);
}
}
}
【讨论】:
在我的场景中,我只需要处理列名(没有单元格编号),并使用 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
要恢复原状,完整代码和测试,请参阅this gist。
【讨论】:
在@petelids 答案中略微修改了 GetColumnIndex 函数。结果将是从零开始的索引。如果需要为从一开始的索引添加 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;
}
【讨论】:
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 是从 1 开始的并且 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
【讨论】: