You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AreaReference.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.util;
  16. import org.apache.poi.ss.SpreadsheetVersion;
  17. import java.util.ArrayList;
  18. import java.util.StringTokenizer;
  19. public class AreaReference {
  20. /** The character (!) that separates sheet names from cell references */
  21. private static final char SHEET_NAME_DELIMITER = '!';
  22. /** The character (:) that separates the two cell references in a multi-cell area reference */
  23. private static final char CELL_DELIMITER = ':';
  24. /** The character (') used to quote sheet names when they contain special characters */
  25. private static final char SPECIAL_NAME_DELIMITER = '\'';
  26. private final CellReference _firstCell;
  27. private final CellReference _lastCell;
  28. private final boolean _isSingleCell;
  29. /**
  30. * Create an area ref from a string representation. Sheet names containing special characters should be
  31. * delimited and escaped as per normal syntax rules for formulas.<br/>
  32. * The area reference must be contiguous (i.e. represent a single rectangle, not a union of rectangles)
  33. */
  34. public AreaReference(String reference) {
  35. if(! isContiguous(reference)) {
  36. throw new IllegalArgumentException(
  37. "References passed to the AreaReference must be contiguous, " +
  38. "use generateContiguous(ref) if you have non-contiguous references");
  39. }
  40. String[] parts = separateAreaRefs(reference);
  41. String part0 = parts[0];
  42. if (parts.length == 1) {
  43. // TODO - probably shouldn't initialize area ref when text is really a cell ref
  44. // Need to fix some named range stuff to get rid of this
  45. _firstCell = new CellReference(part0);
  46. _lastCell = _firstCell;
  47. _isSingleCell = true;
  48. return;
  49. }
  50. if (parts.length != 2) {
  51. throw new IllegalArgumentException("Bad area ref '" + reference + "'");
  52. }
  53. String part1 = parts[1];
  54. if (isPlainColumn(part0)) {
  55. if (!isPlainColumn(part1)) {
  56. throw new RuntimeException("Bad area ref '" + reference + "'");
  57. }
  58. // Special handling for whole-column references
  59. // Represented internally as x$1 to x$65536
  60. // which is the maximum range of rows
  61. boolean firstIsAbs = CellReference.isPartAbsolute(part0);
  62. boolean lastIsAbs = CellReference.isPartAbsolute(part1);
  63. int col0 = CellReference.convertColStringToIndex(part0);
  64. int col1 = CellReference.convertColStringToIndex(part1);
  65. _firstCell = new CellReference(0, col0, true, firstIsAbs);
  66. _lastCell = new CellReference(0xFFFF, col1, true, lastIsAbs);
  67. _isSingleCell = false;
  68. // TODO - whole row refs
  69. } else {
  70. _firstCell = new CellReference(part0);
  71. _lastCell = new CellReference(part1);
  72. _isSingleCell = part0.equals(part1);
  73. }
  74. }
  75. private boolean isPlainColumn(String refPart) {
  76. for(int i=refPart.length()-1; i>=0; i--) {
  77. int ch = refPart.charAt(i);
  78. if (ch == '$' && i==0) {
  79. continue;
  80. }
  81. if (ch < 'A' || ch > 'Z') {
  82. return false;
  83. }
  84. }
  85. return true;
  86. }
  87. /**
  88. * Creates an area ref from a pair of Cell References.
  89. */
  90. public AreaReference(CellReference topLeft, CellReference botRight) {
  91. boolean swapRows = topLeft.getRow() > botRight.getRow();
  92. boolean swapCols = topLeft.getCol() > botRight.getCol();
  93. if (swapRows || swapCols) {
  94. int firstRow;
  95. int lastRow;
  96. int firstColumn;
  97. int lastColumn;
  98. boolean firstRowAbs;
  99. boolean lastRowAbs;
  100. boolean firstColAbs;
  101. boolean lastColAbs;
  102. if (swapRows) {
  103. firstRow = botRight.getRow();
  104. firstRowAbs = botRight.isRowAbsolute();
  105. lastRow = topLeft.getRow();
  106. lastRowAbs = topLeft.isRowAbsolute();
  107. } else {
  108. firstRow = topLeft.getRow();
  109. firstRowAbs = topLeft.isRowAbsolute();
  110. lastRow = botRight.getRow();
  111. lastRowAbs = botRight.isRowAbsolute();
  112. }
  113. if (swapCols) {
  114. firstColumn = botRight.getCol();
  115. firstColAbs = botRight.isColAbsolute();
  116. lastColumn = topLeft.getCol();
  117. lastColAbs = topLeft.isColAbsolute();
  118. } else {
  119. firstColumn = topLeft.getCol();
  120. firstColAbs = topLeft.isColAbsolute();
  121. lastColumn = botRight.getCol();
  122. lastColAbs = botRight.isColAbsolute();
  123. }
  124. _firstCell = new CellReference(firstRow, firstColumn, firstRowAbs, firstColAbs);
  125. _lastCell = new CellReference(lastRow, lastColumn, lastRowAbs, lastColAbs);
  126. } else {
  127. _firstCell = topLeft;
  128. _lastCell = botRight;
  129. }
  130. _isSingleCell = false;
  131. }
  132. /**
  133. * Is the reference for a contiguous (i.e.
  134. * unbroken) area, or is it made up of
  135. * several different parts?
  136. * (If it is, you will need to call
  137. * {@link #generateContiguous(String)})
  138. */
  139. public static boolean isContiguous(String reference) {
  140. // If there's a sheet name, strip it off
  141. int sheetRefEnd = reference.indexOf('!');
  142. if(sheetRefEnd != -1) {
  143. reference = reference.substring(sheetRefEnd);
  144. }
  145. // Check for the , as a sign of non-coniguous
  146. if(reference.indexOf(',') == -1) {
  147. return true;
  148. }
  149. return false;
  150. }
  151. public static AreaReference getWholeRow(String start, String end) {
  152. return new AreaReference("$A" + start + ":$IV" + end);
  153. }
  154. public static AreaReference getWholeColumn(String start, String end) {
  155. return new AreaReference(start + "$1:" + end + "$65536");
  156. }
  157. /**
  158. * Is the reference for a whole-column reference,
  159. * such as C:C or D:G ?
  160. */
  161. public static boolean isWholeColumnReference(CellReference topLeft, CellReference botRight) {
  162. // These are represented as something like
  163. // C$1:C$65535 or D$1:F$0
  164. // i.e. absolute from 1st row to 0th one
  165. if(topLeft.getRow() == 0 && topLeft.isRowAbsolute() &&
  166. botRight.getRow() == SpreadsheetVersion.EXCEL97.getLastRowIndex() && botRight.isRowAbsolute()) {
  167. return true;
  168. }
  169. return false;
  170. }
  171. public boolean isWholeColumnReference() {
  172. return isWholeColumnReference(_firstCell, _lastCell);
  173. }
  174. /**
  175. * Takes a non-contiguous area reference, and
  176. * returns an array of contiguous area references.
  177. */
  178. public static AreaReference[] generateContiguous(String reference) {
  179. ArrayList refs = new ArrayList();
  180. StringTokenizer st = new StringTokenizer(reference, ",");
  181. while(st.hasMoreTokens()) {
  182. refs.add(
  183. new AreaReference(st.nextToken())
  184. );
  185. }
  186. return (AreaReference[])refs.toArray(new AreaReference[refs.size()]);
  187. }
  188. /**
  189. * @return <code>false</code> if this area reference involves more than one cell
  190. */
  191. public boolean isSingleCell() {
  192. return _isSingleCell;
  193. }
  194. /**
  195. * @return the first cell reference which defines this area. Usually this cell is in the upper
  196. * left corner of the area (but this is not a requirement).
  197. */
  198. public CellReference getFirstCell() {
  199. return _firstCell;
  200. }
  201. /**
  202. * Note - if this area reference refers to a single cell, the return value of this method will
  203. * be identical to that of <tt>getFirstCell()</tt>
  204. * @return the second cell reference which defines this area. For multi-cell areas, this is
  205. * cell diagonally opposite the 'first cell'. Usually this cell is in the lower right corner
  206. * of the area (but this is not a requirement).
  207. */
  208. public CellReference getLastCell() {
  209. return _lastCell;
  210. }
  211. /**
  212. * Returns a reference to every cell covered by this area
  213. */
  214. public CellReference[] getAllReferencedCells() {
  215. // Special case for single cell reference
  216. if(_isSingleCell) {
  217. return new CellReference[] { _firstCell, };
  218. }
  219. // Interpolate between the two
  220. int minRow = Math.min(_firstCell.getRow(), _lastCell.getRow());
  221. int maxRow = Math.max(_firstCell.getRow(), _lastCell.getRow());
  222. int minCol = Math.min(_firstCell.getCol(), _lastCell.getCol());
  223. int maxCol = Math.max(_firstCell.getCol(), _lastCell.getCol());
  224. String sheetName = _firstCell.getSheetName();
  225. ArrayList refs = new ArrayList();
  226. for(int row=minRow; row<=maxRow; row++) {
  227. for(int col=minCol; col<=maxCol; col++) {
  228. CellReference ref = new CellReference(sheetName, row, col, _firstCell.isRowAbsolute(), _firstCell.isColAbsolute());
  229. refs.add(ref);
  230. }
  231. }
  232. return (CellReference[])refs.toArray(new CellReference[refs.size()]);
  233. }
  234. /**
  235. * Example return values:
  236. * <table border="0" cellpadding="1" cellspacing="0" summary="Example return values">
  237. * <tr><th align='left'>Result</th><th align='left'>Comment</th></tr>
  238. * <tr><td>A1:A1</td><td>Single cell area reference without sheet</td></tr>
  239. * <tr><td>A1:$C$1</td><td>Multi-cell area reference without sheet</td></tr>
  240. * <tr><td>Sheet1!A$1:B4</td><td>Standard sheet name</td></tr>
  241. * <tr><td>'O''Brien''s Sales'!B5:C6'&nbsp;</td><td>Sheet name with special characters</td></tr>
  242. * </table>
  243. * @return the text representation of this area reference as it would appear in a formula.
  244. */
  245. public String formatAsString() {
  246. // Special handling for whole-column references
  247. if(isWholeColumnReference()) {
  248. return
  249. CellReference.convertNumToColString(_firstCell.getCol())
  250. + ":" +
  251. CellReference.convertNumToColString(_lastCell.getCol());
  252. }
  253. StringBuffer sb = new StringBuffer(32);
  254. sb.append(_firstCell.formatAsString());
  255. if(!_isSingleCell) {
  256. sb.append(CELL_DELIMITER);
  257. if(_lastCell.getSheetName() == null) {
  258. sb.append(_lastCell.formatAsString());
  259. } else {
  260. // don't want to include the sheet name twice
  261. _lastCell.appendCellReference(sb);
  262. }
  263. }
  264. return sb.toString();
  265. }
  266. public String toString() {
  267. StringBuffer sb = new StringBuffer(64);
  268. sb.append(getClass().getName()).append(" [");
  269. sb.append(formatAsString());
  270. sb.append("]");
  271. return sb.toString();
  272. }
  273. /**
  274. * Separates Area refs in two parts and returns them as separate elements in a String array,
  275. * each qualified with the sheet name (if present)
  276. *
  277. * @return array with one or two elements. never <code>null</code>
  278. */
  279. private static String[] separateAreaRefs(String reference) {
  280. // TODO - refactor cell reference parsing logic to one place.
  281. // Current known incarnations:
  282. // FormulaParser.GetName()
  283. // CellReference.separateRefParts()
  284. // AreaReference.separateAreaRefs() (here)
  285. // SheetNameFormatter.format() (inverse)
  286. int len = reference.length();
  287. int delimiterPos = -1;
  288. boolean insideDelimitedName = false;
  289. for(int i=0; i<len; i++) {
  290. switch(reference.charAt(i)) {
  291. case CELL_DELIMITER:
  292. if(!insideDelimitedName) {
  293. if(delimiterPos >=0) {
  294. throw new IllegalArgumentException("More than one cell delimiter '"
  295. + CELL_DELIMITER + "' appears in area reference '" + reference + "'");
  296. }
  297. delimiterPos = i;
  298. }
  299. default:
  300. continue;
  301. case SPECIAL_NAME_DELIMITER:
  302. // fall through
  303. }
  304. if(!insideDelimitedName) {
  305. insideDelimitedName = true;
  306. continue;
  307. }
  308. if(i >= len-1) {
  309. // reference ends with the delimited name.
  310. // Assume names like: "Sheet1!'A1'" are never legal.
  311. throw new IllegalArgumentException("Area reference '" + reference
  312. + "' ends with special name delimiter '" + SPECIAL_NAME_DELIMITER + "'");
  313. }
  314. if(reference.charAt(i+1) == SPECIAL_NAME_DELIMITER) {
  315. // two consecutive quotes is the escape sequence for a single one
  316. i++; // skip this and keep parsing the special name
  317. } else {
  318. // this is the end of the delimited name
  319. insideDelimitedName = false;
  320. }
  321. }
  322. if(delimiterPos < 0) {
  323. return new String[] { reference, };
  324. }
  325. String partA = reference.substring(0, delimiterPos);
  326. String partB = reference.substring(delimiterPos+1);
  327. if(partB.indexOf(SHEET_NAME_DELIMITER) >=0) {
  328. // TODO - are references like "Sheet1!A1:Sheet1:B2" ever valid?
  329. // FormulaParser has code to handle that.
  330. throw new RuntimeException("Unexpected " + SHEET_NAME_DELIMITER
  331. + " in second cell reference of '" + reference + "'");
  332. }
  333. int plingPos = partA.lastIndexOf(SHEET_NAME_DELIMITER);
  334. if(plingPos < 0) {
  335. return new String [] { partA, partB, };
  336. }
  337. String sheetName = partA.substring(0, plingPos + 1); // +1 to include delimiter
  338. return new String [] { partA, sheetName + partB, };
  339. }
  340. }