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