Excel列与数字的转换

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;
        }

这个还是一般的进制算法,从末位开始26^{0},到高位次,26^{n-1}(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”的结果

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rgbhi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值