将数字转换为C#中的字母以便在Microsoft Excel中使用[复制]
可能重复:如何将列号(例如127)转换为excel列(例如AA)
好的,我正在编写一个接受二维数组作为参数的方法 . 我想将这个2d数组放到Excel工作表上,但我需要计算出最终的单元格位置 . 我可以像这样轻松地获得高度:
var height = data.GetLength(1); //`data` is the name of my 2d array
这给了我 Y
轴但是得到我的 X
轴并不容易 . 显然我可以得到这样的数字:
var width = data.GetLength(0);
这给了我一个数字,我想转换成一个字母 . 所以,例如,0是A,1是B,依此类推,直到我们到达26,再次回到A.我确信有一种简单的方法可以做到这一点,但我有一个完整的心理障碍 .
你会怎么做?
谢谢
回答(2)
只需将其转换为char并执行“ToString()” .
using System;
using System.Collections.Generic;
public class MyClass
{
public static void RunSnippet()
{
int myNumber = 65;
string myLetter = ((char) myNumber).ToString();
WL(myLetter);
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
2 years ago
这是一个也处理两个字母列的版本(在Z列之后):