C#:EXCEL列名、列序号之间互相转换

EXCEL的列名与列序号 之前的关系如下

|----|----|
| A | 1 |
| B | 2 |
| C | 3 |
| D | 4 |
| E | 5 |
| F | 6 |
| G | 7 |
| H | 8 |
| I | 9 |
| J | 10 |
| K | 11 |
| L | 12 |
| M | 13 |
| N | 14 |
| O | 15 |
| P | 16 |
| Q | 17 |
| R | 18 |
| S | 19 |
| T | 20 |
| U | 21 |
| V | 22 |
| W | 23 |
| X | 24 |
| Y | 25 |
| Z | 26 |
| AA | 27 |
| AB | 28 |

cs 复制代码
        /// <summary>
        /// 根据给的EXCEL列序号,得出列名字母
        /// </summary>
        /// <param name="iColNum">序号</param>
        /// <returns>列名</returns>
        public string ColNum2Name(int iColNum)
        {
            string result = "";

            if (iColNum < 1 || iColNum > 16384)
            {
                throw new Exception("列号超出范围");
            }

            while (iColNum > 0)
            {
                iColNum--; //列号是从1开始的,字母从0开始的
                result = (char)('A' + iColNum % 26) + result;
                iColNum /= 26;
            }
            return result;
        }

        /// <summary>
        /// 根据给出的EXCEL列名,转换成列序号
        /// </summary>
        /// <param name="sColName">列名</param>
        /// <returns>序号</returns>
        public int ColName2Num(string sColName)
        {
            int result = 0;
            for (int i = 0; i < sColName.Length; i++)
            {
                result *= 26;
                result += sColName[i] - 'A' + 1;
            }
            return result;
        }
相关推荐
CoderYanger13 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
CoderYanger17 小时前
动态规划算法-两个数组的dp(含字符串数组):48.最长重复子数组
java·算法·leetcode·动态规划·1024程序员节
金融小师妹18 小时前
美联储议息夜:基于多智能体决策分歧模型的“鹰派降息”推演
人工智能·深度学习·1024程序员节
金融小师妹21 小时前
基于NLP政策文本分析与多智能体博弈模拟的FOMC决策推演:“美联储传声筒”下的利率路径分歧
大数据·人工智能·深度学习·1024程序员节
ohoy1 天前
EasyPoi 自定义数据处理
excel
ohoy1 天前
easypoi 自定义样式 学生-分数红绿颜色设置
excel
ranchor6661 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
Neoest1 天前
【Java 填坑日记】Excel里的“1.00“存入数据库解密后,Integer说它不认识:一次 NumberFormatException 翻车实录
java·数据库·excel
lzq6031 天前
Python自动化办公:5分钟批量处理Excel数据
python·自动化·excel
oh,huoyuyan1 天前
【实战案例】使用火语言RPA『表格数据提取』组件,批量爬取蔬菜价格+Excel 整理
爬虫·excel·rpa