您的位置:首页 > 其它

Excel列字母和数字的转换

2010-09-13 14:03 573 查看
网上看的,收藏备用

//用于excel表格中列号字转成数字,返回的列号索引从1开始
public  int ToIndex(string columnName)
{
if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+"))
throw new Exception("Invalid parameter");
int index = 0;
char[] chars = columnName.ToUpper().ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
}
return index;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

//用于将数字转成excel表格中列号字母,返回的列号索引从A开始,从A对应1开始
public string ToName(int index)
{
if (index <= 0)
throw new Exception("invaild parameter");

index--;
List<string> chars = new List<string>();
do
{
if (chars.Count > 0)
index--;
chars.Insert(0, ((char)(index % 26 + (int)'A' )).ToString());
index = (int)((index - index % 26) / 26);
} while (index > 0);

return String.Join(string.Empty, chars.ToArray());
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: