Excel標題與索引的對應關係

/// <summary>
        /// 返回對應標題的索引
        /// </summary>
        /// <param name="columnTitle">Excel定義列標題:大寫字母</param>
        /// <returns>索引從0開始</returns>
        public static int GetColumnIndex(string columnTitle)
        {
            int len = columnTitle.Length - 1;
            int index = 0;
            for (int i = len; i >=0; i--)
            {
                index += GetColumnTitleNumber(columnTitle[i])*Convert.ToInt32(Math.Pow(26, len - i));
            }
            return --index;
        }

        private static int GetColumnTitleNumber(char columnTitle)
        {
            int startNumber = Convert.ToInt32('A');
            int currentNumber = Convert.ToInt32(columnTitle);
            if (currentNumber < startNumber || currentNumber >= startNumber + 26)
                throw new ArgumentOutOfRangeException(columnTitle+"列標題超出定義");
            return Convert.ToInt32(columnTitle) - startNumber + 1;
        }

        /// <summary>
        /// 根據列的索引返回對應的標題
        /// </summary>
        /// <param name="columnIndex">列索引從0開始</param>
        /// <returns></returns>
        public static string GetColumnTitle(int columnIndex)
        {
            int columnNumber = columnIndex + 1;
            int left = columnNumber/26;
            int startNumber = Convert.ToInt32('A');
            if (left == 0 || (left == 1 && (columnNumber%26 == 0)))
            {
                return ((char) (startNumber + columnNumber - 1)).ToString();
            }
            if (columnNumber%26 == 0)
                left--;
            return GetColumnTitle(left) + GetColumnTitle(columnNumber - left * 26);
        }
相關文章
相關標籤/搜索