Excel的row letter 和row number的互相转换以及结合Axspreedsheet的应用场景

/// <summary> /// Used to convert Grid's column letters into column numbers, returned column number beginned from "1". /// </summary> public static int ToIndex(string columnName) { if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) throw new Exception("Invalid parameter"); int index = 0; char[] chars = columnName.ToUpper().ToCharArray(); for (int i = 0; i < chars.Length; i++) { index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1); } return index; } /// <summary> /// Used to convert Grid's numbers into column letters, returned column index beginned from 'A', which corresponded by "1". /// </summary> public static string ToName(int index) { if (index <= 0) throw new Exception("invaild parameter"); index--; List<string> chars = new List<string>(); do { if (chars.Count > 0) index--; chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString()); index = (int)((index - index % 26) / 26); } while (index > 0); return String.Join(string.Empty, chars.ToArray()); }

 

然后可以将其和Openxml 以及Axspreedsheet结合进行,以下的例子来自应用Openxml设置单元格格式:

// Convert column number into column letter and join it with row number. string columnLetter = OpenXmlMethod.ToName(SpreadsheetResult.ActiveCell.Column); string currectCoordinate = columnLetter + SpreadsheetResult.ActiveCell.Row; Cell cell = wp.Worksheet.Descendants<Cell>().Where(s1 => s1.CellReference == currectCoordinate).FirstOrDefault();

你可能感兴趣的:(JOIN,exception,String,Excel,Numbers,OpenXml)