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.

XSSFRowColShifter.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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.logging.log4j.LogManager;
  17. import org.apache.logging.log4j.Logger;
  18. import org.apache.poi.ss.formula.FormulaShifter;
  19. import org.apache.poi.ss.formula.FormulaParser;
  20. import org.apache.poi.ss.formula.FormulaType;
  21. import org.apache.poi.ss.formula.FormulaRenderer;
  22. import org.apache.poi.ss.formula.FormulaParseException;
  23. import org.apache.poi.ss.formula.ptg.Ptg;
  24. import org.apache.poi.ss.usermodel.*;
  25. import org.apache.poi.ss.usermodel.helpers.BaseRowColShifter;
  26. import org.apache.poi.ss.util.CellRangeAddress;
  27. import org.apache.poi.util.Internal;
  28. import org.apache.poi.xssf.usermodel.*;
  29. import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
  30. import java.util.ArrayList;
  31. import java.util.List;
  32. import static org.apache.logging.log4j.util.Unbox.box;
  33. /**
  34. * Class for code common to {@link XSSFRowShifter} and {@link XSSFColumnShifter}
  35. *
  36. * @since POI 4.0.0
  37. */
  38. @Internal
  39. /*private*/ final class XSSFRowColShifter {
  40. private static final Logger LOG = LogManager.getLogger(XSSFRowColShifter.class);
  41. private XSSFRowColShifter() { /*no instances for static classes*/}
  42. /**
  43. * Updated named ranges
  44. */
  45. /*package*/
  46. static void updateNamedRanges(Sheet sheet, FormulaShifter formulaShifter) {
  47. Workbook wb = sheet.getWorkbook();
  48. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);
  49. for (Name name : wb.getAllNames()) {
  50. String formula = name.getRefersToFormula();
  51. int sheetIndex = name.getSheetIndex();
  52. final int rowIndex = -1; //don't care, named ranges are not allowed to include structured references
  53. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.NAMEDRANGE, sheetIndex, rowIndex);
  54. if (formulaShifter.adjustFormula(ptgs, sheetIndex)) {
  55. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  56. name.setRefersToFormula(shiftedFmla);
  57. }
  58. }
  59. }
  60. /**
  61. * Update formulas.
  62. */
  63. /*package*/ static void updateFormulas(Sheet sheet, FormulaShifter formulaShifter) {
  64. //update formulas on the parent sheet
  65. updateSheetFormulas(sheet,formulaShifter);
  66. //update formulas on other sheets
  67. Workbook wb = sheet.getWorkbook();
  68. for(Sheet sh : wb)
  69. {
  70. if (sheet == sh) continue;
  71. updateSheetFormulas(sh, formulaShifter);
  72. }
  73. }
  74. /*package*/ static void updateSheetFormulas(Sheet sh, FormulaShifter formulashifter) {
  75. for (Row r : sh) {
  76. XSSFRow row = (XSSFRow) r;
  77. updateRowFormulas(row, formulashifter);
  78. }
  79. }
  80. /**
  81. * Update the formulas in specified row using the formula shifting policy specified by shifter
  82. *
  83. * @param row the row to update the formulas on
  84. * @param formulaShifter the formula shifting policy
  85. */
  86. /*package*/ static void updateRowFormulas(XSSFRow row, FormulaShifter formulaShifter) {
  87. XSSFSheet sheet = row.getSheet();
  88. for (Cell c : row) {
  89. XSSFCell cell = (XSSFCell) c;
  90. CTCell ctCell = cell.getCTCell();
  91. if (ctCell.isSetF()) {
  92. CTCellFormula f = ctCell.getF();
  93. String formula = f.getStringValue();
  94. if (formula.length() > 0) {
  95. String shiftedFormula = shiftFormula(row, formula, formulaShifter);
  96. if (shiftedFormula != null) {
  97. f.setStringValue(shiftedFormula);
  98. if(f.getT() == STCellFormulaType.SHARED){
  99. int si = Math.toIntExact(f.getSi());
  100. CTCellFormula sf = sheet.getSharedFormula(si);
  101. sf.setStringValue(shiftedFormula);
  102. updateRefInCTCellFormula(row, formulaShifter, sf);
  103. }
  104. }
  105. }
  106. //Range of cells which the formula applies to.
  107. updateRefInCTCellFormula(row, formulaShifter, f);
  108. }
  109. }
  110. }
  111. /**
  112. * Shift a formula using the supplied FormulaShifter
  113. *
  114. * @param row the row of the cell this formula belongs to. Used to get a reference to the parent workbook.
  115. * @param formula the formula to shift
  116. * @param formulaShifter the FormulaShifter object that operates on the parsed formula tokens
  117. * @return the shifted formula if the formula was changed,
  118. * <code>null</code> if the formula wasn't modified
  119. */
  120. /*package*/
  121. static String shiftFormula(Row row, String formula, FormulaShifter formulaShifter) {
  122. Sheet sheet = row.getSheet();
  123. Workbook wb = sheet.getWorkbook();
  124. int sheetIndex = wb.getSheetIndex(sheet);
  125. final int rowIndex = row.getRowNum();
  126. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);
  127. try {
  128. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex, rowIndex);
  129. String shiftedFmla = null;
  130. if (formulaShifter.adjustFormula(ptgs, sheetIndex)) {
  131. shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  132. }
  133. return shiftedFmla;
  134. } catch (FormulaParseException fpe) {
  135. // Log, but don't change, rather than breaking
  136. LOG.atWarn().withThrowable(fpe).log("Error shifting formula on row {}", box(row.getRowNum()));
  137. return formula;
  138. }
  139. }
  140. /*package*/
  141. static void updateRefInCTCellFormula(Row row, FormulaShifter formulaShifter, CTCellFormula f) {
  142. if (f.isSetRef()) { //Range of cells which the formula applies to.
  143. String ref = f.getRef();
  144. String shiftedRef = shiftFormula(row, ref, formulaShifter);
  145. if (shiftedRef != null) f.setRef(shiftedRef);
  146. }
  147. }
  148. /*package*/ static void updateConditionalFormatting(Sheet sheet, FormulaShifter formulaShifter) {
  149. XSSFSheet xsheet = (XSSFSheet) sheet;
  150. XSSFWorkbook wb = xsheet.getWorkbook();
  151. int sheetIndex = wb.getSheetIndex(sheet);
  152. final int rowIndex = -1; //don't care, structured references not allowed in conditional formatting
  153. XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
  154. CTWorksheet ctWorksheet = xsheet.getCTWorksheet();
  155. CTConditionalFormatting[] conditionalFormattingArray = ctWorksheet.getConditionalFormattingArray();
  156. // iterate backwards due to possible calls to ctWorksheet.removeConditionalFormatting(j)
  157. for (int j = conditionalFormattingArray.length - 1; j >= 0; j--) {
  158. CTConditionalFormatting cf = conditionalFormattingArray[j];
  159. ArrayList<CellRangeAddress> cellRanges = new ArrayList<>();
  160. for (Object stRef : cf.getSqref()) {
  161. String[] regions = stRef.toString().split(" ");
  162. for (String region : regions) {
  163. cellRanges.add(CellRangeAddress.valueOf(region));
  164. }
  165. }
  166. boolean changed = false;
  167. List<CellRangeAddress> temp = new ArrayList<>();
  168. for (CellRangeAddress craOld : cellRanges) {
  169. CellRangeAddress craNew = BaseRowColShifter.shiftRange(formulaShifter, craOld, sheetIndex);
  170. if (craNew == null) {
  171. changed = true;
  172. continue;
  173. }
  174. temp.add(craNew);
  175. if (craNew != craOld) {
  176. changed = true;
  177. }
  178. }
  179. if (changed) {
  180. int nRanges = temp.size();
  181. if (nRanges == 0) {
  182. ctWorksheet.removeConditionalFormatting(j);
  183. continue;
  184. }
  185. List<String> refs = new ArrayList<>();
  186. for(CellRangeAddress a : temp) refs.add(a.formatAsString());
  187. cf.setSqref(refs);
  188. }
  189. for(CTCfRule cfRule : cf.getCfRuleArray()){
  190. String[] formulaArray = cfRule.getFormulaArray();
  191. for (int i = 0; i < formulaArray.length; i++) {
  192. String formula = formulaArray[i];
  193. Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex, rowIndex);
  194. if (formulaShifter.adjustFormula(ptgs, sheetIndex)) {
  195. String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
  196. cfRule.setFormulaArray(i, shiftedFmla);
  197. }
  198. }
  199. }
  200. }
  201. }
  202. /*package*/ static void updateHyperlinks(Sheet sheet, FormulaShifter formulaShifter) {
  203. final int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet);
  204. for (Hyperlink hyperlink : sheet.getHyperlinkList()) {
  205. XSSFHyperlink xhyperlink = (XSSFHyperlink) hyperlink;
  206. String cellRef = xhyperlink.getCellRef();
  207. CellRangeAddress cra = CellRangeAddress.valueOf(cellRef);
  208. CellRangeAddress shiftedRange = BaseRowColShifter.shiftRange(formulaShifter, cra, sheetIndex);
  209. if (shiftedRange != null && shiftedRange != cra) {
  210. // shiftedRange should not be null. If shiftedRange is null, that means
  211. // that a hyperlink wasn't deleted at the beginning of shiftRows when
  212. // identifying rows that should be removed because they will be overwritten
  213. xhyperlink.setCellReference(shiftedRange.formatAsString());
  214. }
  215. }
  216. }
  217. }