1 16 17 18 package org.apache.poi.hssf.util; 19 20 25 public class CellReference { 26 27 28 private int row; 29 private int col; 30 private String sheetName; 31 private boolean rowAbs; 32 private boolean colAbs; 33 34 public CellReference(String cellRef) { 35 String [] parts = separateRefParts(cellRef); 36 sheetName = parts[0]; 37 String ref = parts[1]; 38 if (ref.charAt(0) == '$') { 39 colAbs=true; 40 ref=ref.substring(1); 41 } 42 col = convertColStringToNum(ref); 43 ref=parts[2]; 44 if (ref.charAt(0) == '$') { 45 rowAbs=true; 46 ref=ref.substring(1); 47 } 48 row = Integer.parseInt(ref)-1; 49 } 50 51 public CellReference(int pRow, int pCol) { 52 this(pRow,pCol,false,false); 53 } 54 55 public CellReference(int pRow, int pCol, boolean pAbsRow, boolean pAbsCol) { 56 row=pRow;col=pCol; 57 rowAbs = pAbsRow; 58 colAbs=pAbsCol; 59 60 } 61 62 public int getRow(){return row;} 63 public short getCol(){return (short) col;} 64 public boolean isRowAbsolute(){return rowAbs;} 65 public boolean isColAbsolute(){return colAbs;} 66 public String getSheetName(){return sheetName;} 67 68 72 private int convertColStringToNum(String ref) { 73 int len = ref.length(); 74 int retval=0; 75 int pos = 0; 76 77 for (int k = ref.length()-1; k > -1; k--) { 78 char thechar = ref.charAt(k); 79 if ( pos == 0) { 80 retval += (Character.getNumericValue(thechar)-9); 81 } else { 82 retval += (Character.getNumericValue(thechar)-9) * (pos * 26); 83 } 84 pos++; 85 } 86 return retval-1; 87 } 88 89 90 95 private String [] separateRefParts(String reference) { 96 97 String retval[] = new String [3]; 101 102 int start = reference.indexOf("!"); 103 if (start != -1) retval[0] = reference.substring(0, start); 104 start += 1; 105 106 int length = reference.length(); 107 108 109 char[] chars = reference.toCharArray(); 110 int loc = start; 111 if (chars[loc]=='$') loc++; 112 for (; loc < chars.length; loc++) { 113 if (Character.isDigit(chars[loc]) || chars[loc] == '$') { 114 break; 115 } 116 } 117 118 retval[1] = reference.substring(start,loc); 119 retval[2] = reference.substring(loc); 120 return retval; 121 } 122 123 126 private static String convertNumToColString(int col) { 127 String retval = null; 128 int mod = col % 26; 129 int div = col / 26; 130 char small=(char)(mod + 65); 131 char big = (char)(div + 64); 132 133 if (div == 0) { 134 retval = ""+small; 135 } else { 136 retval = ""+big+""+small; 137 } 138 139 return retval; 140 } 141 142 143 public String toString() { 144 StringBuffer retval = new StringBuffer (); 145 retval.append( (colAbs)?"$":""); 146 retval.append( convertNumToColString(col)); 147 retval.append((rowAbs)?"$":""); 148 retval.append(row+1); 149 150 return retval.toString(); 151 } 152 } 153 | Popular Tags |