将数字转换为C#中的字母,以便在Microsoft Excel中使用

时间:2012-04-29 15:57:04

标签: c# algorithm excel

  

可能重复:
  How to convert a column number (eg. 127) into an excel column (eg. 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 个答案:

答案 0 :(得分:30)

这是一个也处理双字母列的版本(在Z列之后):

static string GetColumnName(int index)
{
    const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    var value = "";

    if (index >= letters.Length)
        value += letters[index / letters.Length - 1];

    value += letters[index % letters.Length];

    return value;
}

答案 1 :(得分:1)

只需将其转换为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
}