使用一些电子表格内容,列内部的列用简单的十进制数字表示(0索引),但对于输出,我需要它采用标准的人类可读格式:
A, B, C, .. Z, AA, AB, AC, .. AZ, BA ..
我首先想到“简单!我只是切换到基数26并使用[A-Z]而不是[0-9A-P]”,除了使用这种技术使A => 0. B =>因此,序列实际上是这样的:
A, B, .. Y, Z, BA, BB
如何将小数转换为excel样式的列名?
答案 0 :(得分:2)
答案 1 :(得分:0)
这可能不是最有效的方式,但它相当简洁而且有效。可能值得进行范围检查,因为我怀疑在生产代码中它不会超过ZZ
,因为我怀疑会发生不好的事情。当然,如果你不喜欢它们,你可以将条件运算符扩展为if/else
。
static string ColumnPrefix(int column)
{
Debug.Assert(column >= 0, "Column would be below 'A'.");
Debug.Assert(column <= 26 * 27, "Column would be above 'ZZ'.");
Func<int, string> itoa = i => new string((char)('A' + i), 1);
return column < 26 ?
itoa(column) :
itoa((column - 26) / 26) + itoa(column % 26);
}
答案 2 :(得分:0)
在VB .NET代码中使用递归表达性
Function Decimal2ExcelAZ(ByVal number As Integer) As String
If number < 0 Then
Throw New Exception("Number cannot be negative")
ElseIf number < 26 Then
Rem 65 is the ASCII of "A"
Return New String(Chr(65 + number) + "")
Else
Return Decimal2ExcelAZ(number \ 26 - 1) + Decimal2ExcelAZ(number Mod 26)
End If
End Function
答案 3 :(得分:0)
以下是PHP中的解决方案,几乎直接来自this answer的Graham:
function rowCol2Cell($row, $col) {
$dividend = $col + 1;
$columnName = '';
while ($dividend > 0) {
$modulo = ($dividend - 1) % 26;
$columnName = chr(65 + $modulo) . $columnName;
$dividend = (int)(($dividend - $modulo) / 26);
}
return $columnName . ($row + 1);
}
// rowCol2Cell(0, 0) = "A1"
// rowCol2Cell(0, 1) = "B1"
// rowCol2Cell(0,26) = "AA1"
修改强>:
如果您正在使用PHP PEAR模块Spreadsheet Excel Writer,那么它内置了此功能:
Spreadsheet_Excel_Writer::rowcolToCell
我可能应该只是RTFM,嘿......
答案 4 :(得分:0)
没有Java版本就不会完整...
protected static String columnLetter( int columnNumber ) {
if( columnNumber < 0 ) return "Err";
if( columnNumber < 26 )
return Character.toString((char) (columnNumber+ 65));
return columnLetter( (columnNumber / 26) - 1) +
columnLetter ( columnNumber % 26 );
}
(基于递归的VB .NET示例)
答案 5 :(得分:-1)
这是一个VB函数。通过利用模数和对数,它是微不足道的,不需要递归:
Function ColumnLetter(ByVal colNum As Long) As String
Dim i As Long, x As Long
For i = Int(Log(CDbl(25 * (CDbl(colNum) + 1))) / Log(26)) - 1 To 0 Step -1
x = (26 ^ (i + 1) - 1) / 25 - 1
If colNum > x Then
ColumnLetter = ColumnLetter & Chr(((colNum - x - 1) \ 26 ^ i) Mod 26 + 65)
End If
Next i
End Function