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.

XSSFRowShifter.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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.xssf.usermodel.helpers;
  16. import org.apache.poi.xssf.usermodel.*;
  17. import org.apache.poi.ss.util.CellRangeAddress;
  18. import org.apache.poi.ss.formula.FormulaParser;
  19. import org.apache.poi.ss.formula.FormulaType;
  20. import org.apache.poi.ss.formula.FormulaRenderer;
  21. import org.apache.poi.ss.usermodel.Row;
  22. import org.apache.poi.ss.usermodel.Cell;
  23. import org.apache.poi.ss.formula.FormulaShifter;
  24. import org.apache.poi.ss.formula.ptg.Ptg;
  25. import org.apache.poi.ss.formula.ptg.AreaPtg;
  26. import org.apache.poi.ss.formula.ptg.AreaErrPtg;
  27. import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
  28. import java.util.List;
  29. import java.util.ArrayList;
  30. /**
  31. * @author Yegor Kozlov
  32. */
  33. public final class XSSFRowShifter {
  34. private final XSSFSheet sheet;
  35. public XSSFRowShifter(XSSFSheet sh) {
  36. sheet = sh;
  37. }
  38. /**
  39. * Shift merged regions
  40. *
  41. * @param startRow the row to start shifting
  42. * @param endRow the row to end shifting
  43. * @param n the number of rows to shift
  44. * @return an array of affected cell regions
  45. */
  46. public List<CellRangeAddress> shiftMerged(int startRow, int endRow, int n) {
  47. List<CellRangeAddress> shiftedRegions = new ArrayList<CellRangeAddress>();
  48. //move merged regions completely if they fall within the new region boundaries when they are shifted
  49. for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
  50. CellRangeAddress merged = sheet.getMergedRegion(i);
  51. boolean inStart = (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);
  52. boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);
  53. //don't check if it's not within the shifted area
  54. if (!inStart || !inEnd) {
  55. continue;
  56. }
  57. //only shift if the region outside the shifted rows is not merged too
  58. if (!containsCell(merged, startRow - 1, 0) && !containsCell(merged, endRow + 1, 0)) {
  59. merged.setFirstRow(merged.getFirstRow() + n);
  60. merged.setLastRow(merged.getLastRow() + n);
  61. //have to remove/add it back
  62. shiftedRegions.add(merged);
  63. sheet.removeMergedRegion(i);
  64. i = i - 1; // we have to back up now since we removed one
  65. }
  66. }
  67. //read so it doesn't get shifted again
  68. for (CellRangeAddress region : shiftedRegions) {
  69. sheet.addMergedRegion(region);
  70. }
  71. return shiftedRegions;
  72. }
  73. /**
  74. * Check if the row and column are in the specified cell range
  75. *
  76. * @param cr the cell range to check in
  77. * @param rowIx the row to check
  78. * @param colIx the column to check
  79. * @return true if the range contains the cell [rowIx,colIx]
  80. */
  81. private static boolean containsCell(CellRangeAddress cr, int rowIx, int colIx) {
  82. if (cr.getFirstRow() <= rowIx && cr.getLastRow() >= rowIx
  83. && cr.getFirstColumn() <= colIx && cr.getLastColumn() >= colIx) {
  84. return true;
  85. }
  86. return false;
  87. }
  88. /**
  89. * Updated named ranges
  90. */
  91. public void updateNamedRanges(FormulaShifter shifter) {
  92. XSSFWorkbook wb = sheet.getWorkbook();
  93. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  94. for (int i = 0; i < wb.getNumberOfNames(); i++) {
  95. XSSFName name = wb.getNameAt(i);
  96. String formula = name.getRefersToFormula();
  97. int sheetIndex = name.getSheetIndex();
  98. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.NAMEDRANGE, sheetIndex);
  99. if (shifter.adjustFormula(ptgs, sheetIndex)) {
  100. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  101. name.setRefersToFormula(shiftedFmla);
  102. }
  103. }
  104. }
  105. /**
  106. * Update formulas.
  107. */
  108. public void updateFormulas(FormulaShifter shifter) {
  109. //update formulas on the parent sheet
  110. updateSheetFormulas(sheet, shifter);
  111. //update formulas on other sheets
  112. XSSFWorkbook wb = sheet.getWorkbook();
  113. for (XSSFSheet sh : wb) {
  114. if (sheet == sh) continue;
  115. updateSheetFormulas(sh, shifter);
  116. }
  117. }
  118. private void updateSheetFormulas(XSSFSheet sh, FormulaShifter shifter) {
  119. for (Row r : sh) {
  120. XSSFRow row = (XSSFRow) r;
  121. updateRowFormulas(row, shifter);
  122. }
  123. }
  124. private void updateRowFormulas(XSSFRow row, FormulaShifter shifter) {
  125. for (Cell c : row) {
  126. XSSFCell cell = (XSSFCell) c;
  127. CTCell ctCell = cell.getCTCell();
  128. if (ctCell.isSetF()) {
  129. CTCellFormula f = ctCell.getF();
  130. String formula = f.getStringValue();
  131. if (formula.length() > 0) {
  132. String shiftedFormula = shiftFormula(row, formula, shifter);
  133. if (shiftedFormula != null) {
  134. f.setStringValue(shiftedFormula);
  135. if(f.getT() == STCellFormulaType.SHARED){
  136. int si = (int)f.getSi();
  137. CTCellFormula sf = row.getSheet().getSharedFormula(si);
  138. sf.setStringValue(shiftedFormula);
  139. }
  140. }
  141. }
  142. if (f.isSetRef()) { //Range of cells which the formula applies to.
  143. String ref = f.getRef();
  144. String shiftedRef = shiftFormula(row, ref, shifter);
  145. if (shiftedRef != null) f.setRef(shiftedRef);
  146. }
  147. }
  148. }
  149. }
  150. /**
  151. * Shift a formula using the supplied FormulaShifter
  152. *
  153. * @param row the row of the cell this formula belongs to. Used to get a reference to the parent workbook.
  154. * @param formula the formula to shift
  155. * @param shifter the FormulaShifter object that operates on the parsed formula tokens
  156. * @return the shifted formula if the formula was changed,
  157. * <code>null</code> if the formula wasn't modified
  158. */
  159. private static String shiftFormula(XSSFRow row, String formula, FormulaShifter shifter) {
  160. XSSFSheet sheet = row.getSheet();
  161. XSSFWorkbook wb = sheet.getWorkbook();
  162. int sheetIndex = wb.getSheetIndex(sheet);
  163. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  164. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex);
  165. String shiftedFmla = null;
  166. if (shifter.adjustFormula(ptgs, sheetIndex)) {
  167. shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  168. }
  169. return shiftedFmla;
  170. }
  171. public void updateConditionalFormatting(FormulaShifter shifter) {
  172. XSSFWorkbook wb = sheet.getWorkbook();
  173. int sheetIndex = wb.getSheetIndex(sheet);
  174. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  175. List<CTConditionalFormatting> cfList = sheet.getCTWorksheet().getConditionalFormattingList();
  176. for(int j = 0; j< cfList.size(); j++){
  177. CTConditionalFormatting cf = cfList.get(j);
  178. ArrayList<CellRangeAddress> cellRanges = new ArrayList<CellRangeAddress>();
  179. for (Object stRef : cf.getSqref()) {
  180. String[] regions = stRef.toString().split(" ");
  181. for (int i = 0; i < regions.length; i++) {
  182. cellRanges.add(CellRangeAddress.valueOf(regions[i]));
  183. }
  184. }
  185. boolean changed = false;
  186. List<CellRangeAddress> temp = new ArrayList<CellRangeAddress>();
  187. for (int i = 0; i < cellRanges.size(); i++) {
  188. CellRangeAddress craOld = cellRanges.get(i);
  189. CellRangeAddress craNew = shiftRange(shifter, craOld, sheetIndex);
  190. if (craNew == null) {
  191. changed = true;
  192. continue;
  193. }
  194. temp.add(craNew);
  195. if (craNew != craOld) {
  196. changed = true;
  197. }
  198. }
  199. if (changed) {
  200. int nRanges = temp.size();
  201. if (nRanges == 0) {
  202. cfList.remove(j);
  203. continue;
  204. }
  205. List<String> refs = new ArrayList<String>();
  206. for(CellRangeAddress a : temp) refs.add(a.formatAsString());
  207. cf.setSqref(refs);
  208. }
  209. for(CTCfRule cfRule : cf.getCfRuleList()){
  210. List<String> formulas = cfRule.getFormulaList();
  211. for (int i = 0; i < formulas.size(); i++) {
  212. String formula = formulas.get(i);
  213. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex);
  214. if (shifter.adjustFormula(ptgs, sheetIndex)) {
  215. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  216. formulas.set(i, shiftedFmla);
  217. }
  218. }
  219. }
  220. }
  221. }
  222. private static CellRangeAddress shiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx) {
  223. // FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here
  224. AreaPtg aptg = new AreaPtg(cra.getFirstRow(), cra.getLastRow(), cra.getFirstColumn(), cra.getLastColumn(), false, false, false, false);
  225. Ptg[] ptgs = { aptg, };
  226. if (!shifter.adjustFormula(ptgs, currentExternSheetIx)) {
  227. return cra;
  228. }
  229. Ptg ptg0 = ptgs[0];
  230. if (ptg0 instanceof AreaPtg) {
  231. AreaPtg bptg = (AreaPtg) ptg0;
  232. return new CellRangeAddress(bptg.getFirstRow(), bptg.getLastRow(), bptg.getFirstColumn(), bptg.getLastColumn());
  233. }
  234. if (ptg0 instanceof AreaErrPtg) {
  235. return null;
  236. }
  237. throw new IllegalStateException("Unexpected shifted ptg class (" + ptg0.getClass().getName() + ")");
  238. }
  239. }