Excel的列名都是以大写英文字母组成的,比如A-Z表示1-26列,AA表示27列,AZ表示52
数字转列名(C#)
public string GetCol(int col)
{
//col从1开始
string res = "";
//col输入始终为非负数
int remain = (col - 1) % 26;
char addChar = (char)('A' + remain);
res = addChar +res;
col = (col-1) / 26;
while (col >= 1)
{
int left = (col - 1) % 26;
char add = (char)('A' + left);
res = add + res;
col = (col-1) / 26;
}
return res;
}
以英文字母表示数字的特点就是,没有0这个概念,如果是一般的26进制,表示26将是10(两位),而这里是Z(一位,因为没有零)
列名转数字(C#)
//列名转数字
public int GetNum(String col)
{
int res = 0;
int mod = 1;
for (int i = col.Length-1; i >=0 ; i--)
{
char now = col[i];
int diff = now - 'A';
res = res + (diff + 1) * mod;
mod = mod * 26;
}
return res;
}
这个还是一般的进制算法,从末位开始,到高位次,(n位字符),的和
平移选中行n个单位(C#),返回结果行Address
public string RowMove(String raw, int n)
{
string res = "";
//提取数字用
string pattern = @"[0-9]+";
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string[] strList = raw.Split(',');
for (int i = 0; i < strList.Length; i++)
{
MatchCollection mc = reg.Matches(strList[i]);
int temp1 = Convert.ToInt32(mc[0].Value) + n;
int temp2 = Convert.ToInt32(mc[1].Value) + n;
res = res + "$" + temp1 + ":$" + temp2;
if (i != (strList.Length - 1))
{
res = res + ",";
}
}
return res;
}
参数raw为选中行的地址
Excel.Range select = (Excel.Range)Globals.ThisAddIn.Application.Selection;
string raw=select.Address;
例如:
如果设n为1,意思是将选中行平移1行得到的地址,将得到形如“$6:$6,$9:$13”的结果