[英]Get .xlsx column name from index in C#
我想创建一个 function 将数字转换为 .csv 文件列。
例如:
等等..
到目前为止,我已经制作了这个 function:
public class Test
{
public static string GetColumn(int index)
{
StringBuilder col = new StringBuilder();
const int alpha_count = 26;
char alpha = (char)64;
if (index <= alpha_count)
{
col.Append(((char)(alpha + index)).ToString());
}
else
{
// I am stuck here....
}
return col.ToString();
}
static void Main(string[] args)
{
var col = Test.GetColumn(1);
}
}
如果数字超过 26(字母的长度),我就会陷入困境。
这是您提出的问题,但我必须注意,我同意@Martin Holy 的回答:如果可能的话,经过测试的用户权限工具已经过修补。
public static string GetColumn(int index)
{
StringBuilder col = new StringBuilder();
const int alpha_count = 26;
char alpha = (char)64;
int div = index / 26;
if (div > 0)
{
col.Append(((char)(alpha + div)).ToString());
}
col.Append(((char)(alpha + (index - (div * 26)) )).ToString());
return col.ToString();
}
我以前用过这个,应该像你描述的那样工作……这来自……
另外,除非我遗漏了什么……不会 29 -> AC?
… 26=Z、27=AA、28=AB 和 29=AC …
private static string ColumnIndexToColumnLetter(int colIndex) {
int div = colIndex;
string colLetter = String.Empty;
int mod = 0;
while (div > 0) {
mod = (div - 1) % 26;
colLetter = (char)(65 + mod) + colLetter;
div = (int)((div - mod) / 26);
}
return colLetter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.