将数字转换为C#中用于Microsoft Excel的字母 [英] Convert a number to a letter in C# for use in Microsoft Excel

查看:217
本文介绍了将数字转换为C#中用于Microsoft Excel的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何将列号(例如127)转换为excel列(例如AA)

好的,所以我正在编写一个接受一个2d数组作为参数的方法。我想把这个2d数组放在Excel工作表上,但是我需要找出最后的单元格位置。我可以很容易地得到这样的高度:

Ok so I am writing a method which accepts a 2d array as a parameter. I want to put this 2d array onto an Excel worksheet but I need to work out the final cell location. I can get the height easily enough like so:

var height = data.GetLength(1); //`data` is the name of my 2d array

这给了我我的 Y 轴,但不太容易得到我的 X 轴。显然我可以得到这样的数字:

This gives me my Y axis but it's not so easy to get my X axis. Obviously I can get the number like so:

var width = data.GetLength(0);

这给我一个号码,我想转换成一封信。所以,例如,0是A,1是B等等,直到我们达到26,再次回到A。我相信有一个简单的方法可以做到这一点,但是我有一个完全的心理障碍。

This gives me a number, which I want to convert to a letter. So, for example, 0 is A, 1 is B and so on until we get to 26 which goes back to A again. I am sure that there is a simple way to do this but I have a total mental block.

你会做什么?

谢谢

推荐答案

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

Here's a version that also handles two-letter columns (after column 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;
}

这篇关于将数字转换为C#中用于Microsoft Excel的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆