/** * Create an cell ref from a string representation. Sheet names containing special characters should be * delimited and escaped as per normal syntax rules for formulas. */ public CellReference(String cellRef) { if (cellRef.EndsWith("#REF!", StringComparison.CurrentCulture)) { throw new ArgumentException("Cell reference invalid: " + cellRef); } CellRefPartsInner parts = SeparateRefParts(cellRef); _sheetName = parts.sheetName; //parts[0]; String colRef = parts.colRef; // parts[1]; //if (colRef.Length < 1) //{ // throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'"); //} _isColAbs = (colRef.Length > 0) && colRef[0] == '$'; //_isColAbs = colRef[0] == '$'; if (_isColAbs) { colRef = colRef.Substring(1); } if (colRef.Length == 0) { _colIndex = -1; } else { _colIndex = ConvertColStringToIndex(colRef); } String rowRef = parts.rowRef;// parts[2]; //if (rowRef.Length < 1) //{ // throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'"); //} //_isRowAbs = rowRef[0] == '$'; _isRowAbs = (rowRef.Length > 0) && rowRef[0] == '$'; if (_isRowAbs) { rowRef = rowRef.Substring(1); } if (rowRef.Length == 0) { _rowIndex = -1; } else { _rowIndex = int.Parse(rowRef, CultureInfo.InvariantCulture) - 1; // -1 to convert 1-based to zero-based } }
/** * Separates the row from the columns and returns an array of three Strings. The first element * is the sheet name. Only the first element may be null. The second element in is the column * name still in ALPHA-26 number format. The third element is the row. */ private static CellRefPartsInner SeparateRefParts(String reference) { int plingPos = reference.LastIndexOf(SHEET_NAME_DELIMITER); String sheetName = ParseSheetName(reference, plingPos); int start = plingPos + 1; String cell = reference.Substring(plingPos + 1).ToUpper(CultureInfo.CurrentCulture); Match matcher = CELL_REF_PATTERN.Match(cell); if (!matcher.Success) { throw new ArgumentException("Invalid CellReference: " + reference); } String col = matcher.Groups[1].Value; String row = matcher.Groups[2].Value; CellRefPartsInner cellRefParts = new CellRefPartsInner(sheetName, row, col); return(cellRefParts); }