PageRenderTime 123ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/org/comsoft/juniprint/utils/ExcelUtils.java

https://bitbucket.org/openicar/juniprint
Java | 1375 lines | 1142 code | 158 blank | 75 comment | 387 complexity | c11a8c0e57714af4cf1eeffb5ef652f0 MD5 | raw file
Possible License(s): Apache-2.0
  1. /*-
  2. * #%L
  3. * uniprint port for java environment
  4. * %%
  5. * Copyright (C) 2012 - 2017 COMSOFT, JSC
  6. * %%
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * #L%
  19. */
  20. package org.comsoft.juniprint.utils;
  21. import java.io.IOException;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.Date;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Iterator;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Set;
  31. import java.util.regex.Matcher;
  32. import java.util.regex.Pattern;
  33. import org.apache.poi.hssf.usermodel.HSSFCell;
  34. import org.apache.poi.hssf.usermodel.HSSFComment;
  35. import org.apache.poi.hssf.usermodel.HSSFName;
  36. import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
  37. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  38. import org.apache.poi.hssf.usermodel.HSSFRow;
  39. import org.apache.poi.hssf.usermodel.HSSFSheet;
  40. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  41. import org.apache.poi.ss.util.AreaReference;
  42. import org.apache.poi.ss.util.CellRangeAddress;
  43. import org.apache.poi.ss.util.CellRangeAddressList;
  44. import org.apache.poi.ss.util.CellReference;
  45. import org.comsoft.juniprint.JUniPrintException;
  46. public class ExcelUtils {
  47. public static final Integer xlMaxNumRow = 65536; //число строк на листе
  48. public static final Integer xlMaxNumCol = 256; //число строк на листе
  49. public static final Byte xlAll = 0;
  50. public static final Byte xlAllExceptBorders = 1;
  51. public static final Byte xlColumnWidths = 2;
  52. public static final Byte xlComments = 3;
  53. public static final Byte xlFormats = 4;
  54. public static final Byte xlFormulas = 5;
  55. public static final Byte xlFormulasAndNumberFormats = 6;
  56. public static final Byte xlValidation = 7;
  57. public static final Byte xlValues = 8;
  58. public static final Byte xlValuesAndNumberFormats = 9;
  59. public static enum XlCellType {xlCellTypeAllFormatConditions,
  60. xlCellTypeAllValidation,
  61. xlCellTypeBlanks,
  62. xlCellTypeComments,
  63. xlCellTypeConstants,
  64. xlCellTypeFormulas,
  65. xlCellTypeLastCell,
  66. xlCellTypeSameFormatConditions,
  67. xlCellTypeSameValidation,
  68. xlCellTypeVisible};
  69. public static enum XlSearchDirection {xlNext, xlPrevious}
  70. public static enum XlLookAt {xlWhole, xlPart}
  71. public static enum XlLookIn {xlValues, xlFormulas, xlComments}
  72. public static float Factotr_MM_Points = 0.3528f;
  73. public static float Factotr_MM_Inches = 25.4f;
  74. public static final Map<Short, float[]> PrintPagesFormat;
  75. static {
  76. Map<Short, float[]> page = new HashMap<Short, float[]>();
  77. page.put(HSSFPrintSetup.A4_PAPERSIZE, new float[]{210f, 297f});
  78. page.put(HSSFPrintSetup.A5_PAPERSIZE, new float[]{148f, 210f});
  79. page.put(HSSFPrintSetup.LEGAL_PAPERSIZE, new float[]{215.9f, 355.6f});
  80. page.put(HSSFPrintSetup.LETTER_PAPERSIZE, new float[]{215.9f, 279.4f});
  81. PrintPagesFormat = java.util.Collections.unmodifiableMap(page);
  82. }
  83. public static HSSFName createNameRange(String name, String refersToR1C1, HSSFWorkbook wb){
  84. if(wb==null) return null;
  85. HSSFName nameRange = wb.createName();
  86. nameRange.setNameName(name);
  87. nameRange.setRefersToFormula(refersToR1C1);
  88. return nameRange;
  89. }
  90. public static AreaReference getReferanceNameRange(HSSFName nameRange){
  91. if (nameRange == null) return null;
  92. return new AreaReference(nameRange.getRefersToFormula());
  93. }
  94. public static HSSFName getNamedRangeInSheets(Map<String, Map<String, HSSFName>> mapWbNames, String name, String[] sheetNames){
  95. if((sheetNames==null) || (sheetNames.length==0)) return null;
  96. if(mapWbNames==null) return null;
  97. for(int iShName = 0; iShName < sheetNames.length; iShName++){
  98. Map<String, HSSFName> mapShNames = mapWbNames.get(sheetNames[iShName]);
  99. if(mapShNames!=null){
  100. HSSFName nameFound = mapShNames.get(name);
  101. if(nameFound != null){
  102. return nameFound;
  103. }
  104. }
  105. }
  106. return null;
  107. }
  108. public static void upadteRowBrokenAfter(HSSFSheet sh, int beforeIndexInsertRow, int countInsertRow, byte factor){
  109. int[] arrIndexRowBroken = sh.getRowBreaks();
  110. for(int indexRow:arrIndexRowBroken){
  111. if (indexRow >= beforeIndexInsertRow) {
  112. sh.removeRowBreak(indexRow);
  113. }
  114. }
  115. for(int indexRow:arrIndexRowBroken){
  116. if (indexRow >= beforeIndexInsertRow) {
  117. sh.setRowBreak(indexRow+countInsertRow*factor);
  118. }
  119. }
  120. }
  121. public static void upadteRowBrokenAfterInsertRows(HSSFSheet sh, int beforeIndexInsertRow, int countInsertRow){
  122. upadteRowBrokenAfter(sh, beforeIndexInsertRow, countInsertRow, (byte)-1);
  123. }
  124. public static void upadteRowBrokenAfterHiddenRows(HSSFSheet sh, int beforeIndexInsertRow, int countInsertRow){
  125. upadteRowBrokenAfter(sh, beforeIndexInsertRow, countInsertRow, (byte)1);
  126. }
  127. public static List<String> upadteReferenceNameAfterInsertRows(Map<String, Map<String, HSSFName>> mapWbNames, String[] sheetNames, int beforeIndexInsertRow, int countInsertRow){
  128. List<String> list = new ArrayList<String>();
  129. /*
  130. if((sheetNames==null) || (sheetNames.length==0)) return list;
  131. if(mapWbNames==null) return list;
  132. for(int iShName = 0; iShName < sheetNames.length; iShName++){
  133. Map<String, HSSFName> mapShNames = mapWbNames.get(sheetNames[iShName]);
  134. if(mapShNames!=null){
  135. for(String key:mapShNames.keySet()){
  136. HSSFName name = mapShNames.get(key);
  137. AreaReference areaRef = new AreaReference(name.getReference());
  138. if (areaRef.isSingleCell())
  139. if(areaRef.getFirstCell().getRow() > beforeIndexInsertRow){
  140. int row = areaRef.getFirstCell().getRow()+countInsertRow+1;
  141. if (row >= 0)
  142. name.setReference(sheetNames[iShName]+"!$"+xlc(areaRef.getFirstCell().getCol()+1)+"$"+(areaRef.getFirstCell().getRow()+countInsertRow+1));
  143. else list.add(key);
  144. }
  145. }
  146. }
  147. }
  148. */
  149. return list;
  150. }
  151. public static Map<String, Map<String, HSSFName>> createNamesMap(HSSFWorkbook wb){
  152. Map<String, Map<String, HSSFName>> mapWbNames = new HashMap<String, Map<String, HSSFName>>();
  153. for(int i = 0, n = wb.getNumberOfNames(); i < n; i++){
  154. HSSFName iName = wb.getNameAt(i);
  155. if(iName!=null){
  156. String iNameName = iName.getNameName();
  157. try{
  158. String iShName = iName.getSheetName();
  159. Map<String, HSSFName> mapShNames = mapWbNames.get(iShName);
  160. if(mapShNames==null){
  161. mapShNames = new HashMap<String, HSSFName>();
  162. mapWbNames.put(iShName, mapShNames);
  163. }
  164. HSSFName name = mapShNames.get(iNameName);
  165. if(name==null){
  166. mapShNames.put(iNameName, iName);
  167. }
  168. }catch(ArrayIndexOutOfBoundsException e){
  169. }
  170. }
  171. }
  172. return mapWbNames;
  173. }
  174. public static int realLastColumnHide(HSSFSheet sh){
  175. int maxLastColumn = 0, lastColumn = 0;
  176. Iterator rowIt = sh.rowIterator();
  177. while(rowIt.hasNext()){
  178. HSSFRow row = (HSSFRow)rowIt.next();
  179. lastColumn = row.getLastCellNum();
  180. if (lastColumn > maxLastColumn) maxLastColumn = lastColumn;
  181. }
  182. return maxLastColumn>0?maxLastColumn-1:0;
  183. }
  184. public static int realLastRow(HSSFSheet sh){
  185. return sh.getLastRowNum();
  186. }
  187. public static HSSFRow getRow(HSSFSheet sh, int rowIndex){
  188. if(sh==null) return null;
  189. HSSFRow r = sh.getRow(rowIndex);
  190. if(r != null) return r;
  191. r = sh.createRow(rowIndex);
  192. return r;
  193. }
  194. public static Boolean hasFormula(HSSFSheet sh, int row, int col){
  195. return hasFormula(sh, new AreaReference(new CellReference(row, col),
  196. new CellReference(row, col)));
  197. }
  198. public static Boolean hasFormula(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol){
  199. return hasFormula(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  200. new CellReference(botRightRow, botRightCol)));
  201. }
  202. public static Boolean hasFormula (HSSFSheet sh, CellReference topLeft, CellReference botRight){
  203. return hasFormula(sh, new AreaReference(topLeft, botRight));
  204. }
  205. public static Boolean hasFormula(HSSFSheet sh, String strAreaRef){
  206. return hasFormula(sh, new AreaReference(strAreaRef));
  207. }
  208. public static Boolean hasFormula (HSSFSheet sh, AreaReference areaRef){
  209. return hasFormula(sh, new CellRangeAddress(areaRef.getFirstCell().getRow(), areaRef.getLastCell().getRow(),
  210. areaRef.getFirstCell().getCol(), areaRef.getLastCell().getCol()));
  211. }
  212. public static Boolean hasFormula (HSSFSheet sh, CellRangeAddress cRA){
  213. boolean isNotFormula = false;
  214. boolean isFormula = false;
  215. for(int row=cRA.getFirstRow(); row <= cRA.getLastRow(); row++){
  216. HSSFRow r = sh.getRow(row);
  217. if (r != null)
  218. for(int col=cRA.getFirstColumn(); col <= cRA.getLastColumn(); col++){
  219. HSSFCell cell = r.getCell(col);
  220. if (cell == null) isNotFormula =true;
  221. else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) isFormula = true;
  222. else isNotFormula =true;
  223. }
  224. else isNotFormula =true;
  225. }
  226. if (!isNotFormula){
  227. if (!isFormula) return false;
  228. else return null;
  229. }
  230. else if (isFormula) return true;
  231. else return null;
  232. }
  233. public static Boolean hasFormulaRow (HSSFSheet sh, int indexRow){
  234. HSSFRow r = sh.getRow(indexRow);
  235. if(r == null) return false;
  236. else {
  237. Iterator it = r.cellIterator();
  238. int countCells = 0;
  239. boolean isFormula = false;
  240. boolean isNotFormula = false;
  241. while (it.hasNext()){
  242. HSSFCell cell = (HSSFCell)it.next();
  243. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) isFormula = true;
  244. else isNotFormula = true;
  245. countCells++;
  246. }
  247. if(isFormula){
  248. if (!isNotFormula) return true;
  249. else return null;
  250. }else return false;
  251. }
  252. }
  253. public static Boolean hasFormulaRow (HSSFSheet sh, int indexFirstRow, int indexLastRow){
  254. boolean isNotFormula = false;
  255. for(int row =indexFirstRow; row <=indexLastRow; row++){
  256. Boolean res = hasFormulaRow (sh, row);
  257. if (res == null) return res;
  258. else if (!res) isNotFormula = true;
  259. }
  260. if(isNotFormula) return false;
  261. else return true;
  262. }
  263. public static void clearColumn(HSSFSheet sh, int indexColumn){
  264. Iterator it = sh.rowIterator();
  265. while(it.hasNext()){
  266. HSSFRow r = (HSSFRow)it.next();
  267. HSSFCell cell = r.getCell(indexColumn);
  268. if (cell != null) r.removeCell(cell);
  269. }
  270. }
  271. public static void clear(HSSFSheet sh, String strRef){
  272. clear(sh, new AreaReference(strRef));
  273. }
  274. public static void clear(HSSFSheet sh, CellReference cellRef){
  275. clear(sh, new AreaReference(cellRef, cellRef));
  276. }
  277. public static void clear(HSSFSheet sh, AreaReference aRef){
  278. for(int row = aRef.getFirstCell().getRow(); row <= aRef.getLastCell().getRow(); row++){
  279. HSSFRow r = sh.getRow(row);
  280. if (r !=null)
  281. for(int col = aRef.getFirstCell().getCol(); col <= aRef.getLastCell().getCol(); col++){
  282. HSSFCell cell = r.getCell(col);
  283. if (cell != null) r.removeCell(cell);
  284. }
  285. }
  286. }
  287. public static HSSFCell getCell(HSSFRow row, int columnIndex){
  288. if(row==null) return null;
  289. HSSFCell c = row.getCell(columnIndex);
  290. if(c != null) return c;
  291. c = row.createCell(columnIndex);
  292. return c;
  293. }
  294. public static HSSFCell getCell(HSSFSheet sh, int rowIndex, int columnIndex){
  295. return getCell(getRow(sh, rowIndex), columnIndex);
  296. }
  297. public static Object getCellValue(HSSFCell cell){
  298. return getCellValue(cell, true, true);
  299. }
  300. /**
  301. *
  302. * @param cell
  303. * @param stringAsJavaLangString
  304. * @param formulaAsNull
  305. * @return
  306. */
  307. public static Object getCellValue(
  308. HSSFCell cell,
  309. boolean stringAsJavaLangString,
  310. boolean formulaAsNull
  311. ){
  312. switch(cell.getCellType()){
  313. case HSSFCell.CELL_TYPE_BLANK:
  314. return null;
  315. case HSSFCell.CELL_TYPE_BOOLEAN:
  316. return cell.getBooleanCellValue();
  317. case HSSFCell.CELL_TYPE_ERROR:
  318. return null;
  319. case HSSFCell.CELL_TYPE_NUMERIC:
  320. if (cell.getCellStyle().getDataFormat() == 14){
  321. return cell.getDateCellValue();
  322. }
  323. return cell.getNumericCellValue();
  324. case HSSFCell.CELL_TYPE_STRING:
  325. if(stringAsJavaLangString){
  326. HSSFRichTextString rich = cell.getRichStringCellValue();
  327. return (rich==null)? null: rich.getString();
  328. }else{
  329. return cell.getRichStringCellValue();
  330. }
  331. case HSSFCell.CELL_TYPE_FORMULA:
  332. return formulaAsNull? null: cell.getCellFormula();
  333. }
  334. return null;
  335. }
  336. public static void setCellValue(HSSFCell cell, Object value){
  337. setCellValue(cell, value, null);
  338. }
  339. public static void setCellValue(HSSFCell cell, Object value, String nullValue){
  340. if(value==null){
  341. if(nullValue != null){
  342. cell.setCellValue(new HSSFRichTextString(nullValue.toString()));
  343. }else{
  344. cell.setCellValue((HSSFRichTextString)null);
  345. }
  346. }else{
  347. if(value instanceof Number){
  348. Number numValue = (Number)value;
  349. cell.setCellValue(numValue.doubleValue());
  350. }else if(value instanceof Boolean){
  351. Boolean boolValue = (Boolean)value;
  352. cell.setCellValue(boolValue.booleanValue());
  353. }else if(value instanceof Date){
  354. Date dateValue = (Date)value;
  355. cell.setCellValue(dateValue);
  356. }else if(value instanceof HSSFRichTextString){
  357. cell.setCellValue((HSSFRichTextString)value);
  358. }else{
  359. String strValue = value.toString();
  360. cell.setCellValue(new HSSFRichTextString(strValue));
  361. }
  362. }
  363. }
  364. public static CellRangeAddress intersectRectangular(CellRangeAddress crA, CellRangeAddress crB){
  365. boolean isIntersect = !( crB.getFirstColumn() > crA.getLastColumn()
  366. || crB.getLastColumn() < crA.getFirstColumn()
  367. || crB.getFirstRow() > crA.getLastRow()
  368. || crB.getLastRow() < crA.getFirstRow()
  369. );
  370. if (isIntersect){
  371. return
  372. new CellRangeAddress(Math.max(crA.getFirstRow(), crB.getFirstRow()),
  373. Math.min(crA.getLastRow(), crB.getLastRow()),
  374. Math.max(crA.getFirstColumn(), crB.getFirstColumn()),
  375. Math.min(crA.getLastColumn(), crB.getLastColumn()));
  376. }
  377. else return null;
  378. }
  379. public static CellRangeAddress unionRectangular(CellRangeAddress crA, CellRangeAddress crB){
  380. boolean isUnion = (crB.getFirstColumn() == crA.getFirstColumn() &&
  381. crB.getLastColumn() == crA.getLastColumn() &&
  382. (Math.abs(crB.getLastRow()- crA.getFirstRow()) == 1 ||
  383. Math.abs(crB.getFirstRow()- crA.getLastRow())==1)) ||
  384. (crB.getFirstRow() == crA.getFirstRow() && crB.getLastRow() == crA.getLastRow() &&
  385. (Math.abs(crB.getLastColumn() - crA.getFirstColumn()) == 1 ||
  386. Math.abs(crB.getFirstColumn()-crA.getLastColumn())==1));
  387. if (isUnion){
  388. return
  389. new CellRangeAddress(Math.min(crA.getFirstRow(), crB.getFirstRow()),
  390. Math.max(crA.getLastRow(), crB.getLastRow()),
  391. Math.min(crA.getFirstColumn(), crB.getFirstColumn()),
  392. Math.max(crA.getLastColumn(), crB.getLastColumn()));
  393. }
  394. else return null;
  395. }
  396. private static CellRangeAddressList unionAllRectangular(List<List<CellRangeAddress>> rangeListForColumns){
  397. CellRangeAddressList rangeList = new CellRangeAddressList();
  398. if (rangeListForColumns.size() > 1){
  399. List<CellRangeAddress> resList = rangeListForColumns.get(rangeListForColumns.size()-1);
  400. for(int col = rangeListForColumns.size()-2; col <= 0; col--){
  401. List<CellRangeAddress> rangeListForColumn = rangeListForColumns.get(col);
  402. CellRangeAddress cRA = null;
  403. for(int row =0; row < resList.size(); row++){
  404. cRA = resList.get(row);
  405. CellRangeAddress res = null;
  406. int countRow =0;
  407. while(countRow < rangeListForColumn.size() || res != null)
  408. res = unionRectangular(cRA, rangeListForColumn.get(countRow++));
  409. if (res == null) resList.add(cRA);
  410. else {
  411. resList.add(res);
  412. rangeListForColumn.remove(countRow-1);
  413. }
  414. }
  415. resList.addAll(rangeListForColumn);
  416. }
  417. for(CellRangeAddress crA:rangeListForColumns.get(0)) rangeList.addCellRangeAddress(crA);
  418. }
  419. else if (rangeListForColumns.size() == 1) {
  420. for(CellRangeAddress crA:rangeListForColumns.get(0)) rangeList.addCellRangeAddress(crA);
  421. }
  422. return rangeList;
  423. }
  424. public static CellRangeAddressList getSpecialCells(HSSFSheet sh, CellRangeAddress cellRef0, XlCellType xlCellType){
  425. CellRangeAddressList rangeList = new CellRangeAddressList();
  426. switch (xlCellType){
  427. case xlCellTypeAllValidation:
  428. /*
  429. for(Object obj: sh.getDVRecords()){
  430. DVRecord dv = (DVRecord)obj;
  431. for(CellRangeAddress cellRef:dv.getCellRangeAddress().getCellRangeAddresses()){
  432. CellRangeAddress cellRange = intersectRectangular(cellRef, cellRef0);
  433. if (cellRange != null) {
  434. if (rangeList == null) rangeList = new CellRangeAddressList();
  435. rangeList.addCellRangeAddress(cellRange);
  436. }
  437. }
  438. }
  439. */
  440. break;
  441. case xlCellTypeVisible:
  442. List<List<CellRangeAddress>> rangeListForColumns = new ArrayList<List<CellRangeAddress>>();
  443. for(int col = cellRef0.getFirstColumn(); col <= cellRef0.getLastColumn(); col++)
  444. if(sh.getColumnWidth(col)!=0){
  445. List<CellRangeAddress> rangeListForColumn = new ArrayList<CellRangeAddress>();
  446. for(int row = cellRef0.getFirstRow(); row <= cellRef0.getLastRow(); row++)
  447. if(!getRow(sh, row).getZeroHeight()){
  448. CellRangeAddress cRA = new CellRangeAddress(row, row, col, col);
  449. int countRanges = rangeListForColumn.size();
  450. if (countRanges > 0){
  451. CellRangeAddress cRB = rangeListForColumn.get(countRanges-1);
  452. CellRangeAddress res = unionRectangular(cRB, cRA);
  453. if (res != null){
  454. rangeListForColumn.remove(countRanges-1);
  455. rangeListForColumn.add(res);
  456. }else{
  457. rangeListForColumn.add(cRA);
  458. }
  459. }else
  460. rangeListForColumn.add(cRA);
  461. }
  462. if (rangeListForColumn.size() > 0) rangeListForColumns.add(rangeListForColumn);
  463. }
  464. rangeList = unionAllRectangular(rangeListForColumns);
  465. break;
  466. case xlCellTypeFormulas:
  467. rangeListForColumns = new ArrayList<List<CellRangeAddress>>();
  468. for(int col = cellRef0.getFirstColumn(); col <= cellRef0.getLastColumn(); col++){
  469. List<CellRangeAddress> rangeListForColumn = new ArrayList<CellRangeAddress>();
  470. for(int row = cellRef0.getFirstRow(); row <= cellRef0.getLastRow(); row++){
  471. HSSFCell cell = getCell(getRow(sh, row), col);
  472. if (cell.getCellType()== HSSFCell.CELL_TYPE_FORMULA){
  473. CellRangeAddress cRA = new CellRangeAddress(row, row, col, col);
  474. int countRanges = rangeListForColumn.size();
  475. if (countRanges > 0){
  476. CellRangeAddress cRB = rangeListForColumn.get(countRanges-1);
  477. CellRangeAddress res = unionRectangular(cRB, cRA);
  478. if (res != null){
  479. rangeListForColumn.remove(countRanges-1);
  480. rangeListForColumn.add(res);
  481. }else{
  482. rangeListForColumn.add(cRA);
  483. }
  484. }else rangeListForColumn.add(cRA);
  485. }
  486. }
  487. if (rangeListForColumn.size() > 0) rangeListForColumns.add(rangeListForColumn);
  488. }
  489. rangeList = unionAllRectangular(rangeListForColumns);
  490. break;
  491. }
  492. return rangeList.countRanges() > 0?rangeList:null;
  493. }
  494. public static void fillCol(HSSFSheet sh, int col, Object valueFill, byte lookIn){
  495. fill(sh, new AreaReference(new CellReference(0, col),
  496. new CellReference(xlMaxNumRow-1, col)), valueFill, lookIn);
  497. }
  498. public static void fillRow(HSSFSheet sh, int row, Object valueFill, byte lookIn){
  499. fill(sh, new AreaReference(new CellReference(row, 0),
  500. new CellReference(row, xlMaxNumCol-1)), valueFill, lookIn);
  501. }
  502. public static void fillPathRow(HSSFSheet sh, int row, int leftCol, int rightCol, Object valueFill, byte lookIn){
  503. fill(sh, new AreaReference(new CellReference(row, leftCol),
  504. new CellReference(row, rightCol)), valueFill, lookIn);
  505. }
  506. public static void fillPathCol(HSSFSheet sh, int col, int topRow, int bottomRow, Object valueFill, byte lookIn){
  507. fill(sh, new AreaReference(new CellReference(topRow, col),
  508. new CellReference(bottomRow, col)), valueFill, lookIn);
  509. }
  510. public static void fill(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, Object valueFill, byte lookIn){
  511. fill(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  512. new CellReference(botRightRow, botRightCol)), valueFill, lookIn);
  513. }
  514. public static void fill(HSSFSheet sh, CellReference topLeft, CellReference botRight, Object valueFill, byte lookIn){
  515. fill(sh, new AreaReference(topLeft, botRight), valueFill, lookIn);
  516. }
  517. public static void fill(HSSFSheet sh, String strAreaRef, Object valueFill, byte lookIn){
  518. fill(sh, new AreaReference(strAreaRef), valueFill, lookIn);
  519. }
  520. public static void fill(HSSFSheet sh, CellRangeAddress cellsRef, Object valueFill, byte lookIn){
  521. fill(sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  522. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), valueFill, lookIn);
  523. }
  524. public static void fill(HSSFSheet sh, AreaReference areaRef, Object valueFill, byte lookIn){
  525. if (lookIn == xlFormulas && ! (valueFill instanceof String)) return;
  526. for(CellReference cellRef:areaRef.getAllReferencedCells()){
  527. if (lookIn == xlValues){
  528. setCellValue(getCell(sh, cellRef.getRow(), cellRef.getCol()), valueFill);
  529. }else if(lookIn == xlFormulas){
  530. HSSFCell cell = getCell(sh, cellRef.getRow(), cellRef.getCol());
  531. cell.setCellFormula((String)valueFill);
  532. }
  533. }
  534. }
  535. public static boolean equalsRectangularAreas(CellRangeAddress cRA1, CellRangeAddress cRA2){
  536. return (cRA1.getLastRow()-cRA1.getFirstRow() == cRA2.getLastRow()-cRA2.getFirstRow() &&
  537. cRA1.getLastColumn()-cRA1.getFirstColumn() == cRA2.getLastColumn()-cRA2.getFirstColumn());
  538. }
  539. public static void fill(HSSFSheet sh, CellRangeAddress srcCRA, CellRangeAddress distCRA, byte lookIn){
  540. if (equalsRectangularAreas(srcCRA, distCRA) && intersectRectangular(srcCRA, distCRA) == null){
  541. int countRow =0;
  542. for(int row = distCRA.getFirstRow(); row <=distCRA.getLastRow(); row++){
  543. HSSFRow distRow = getRow(sh, row);
  544. HSSFRow srcRow = getRow(sh, srcCRA.getFirstRow()+(countRow++));
  545. int countCol =0;
  546. for(int col = distCRA.getFirstColumn(); col <=distCRA.getLastColumn(); col++){
  547. HSSFCell distCell = getCell(distRow, col);
  548. HSSFCell srcCell = getCell(srcRow, srcCRA.getFirstColumn()+(countCol++));
  549. if (lookIn == xlValues){
  550. setCellValue(distCell, getCellValue(srcCell));
  551. }else if(lookIn == xlFormulas){
  552. distCell.setCellFormula(srcCell.getCellFormula());
  553. }
  554. }
  555. }
  556. }
  557. }
  558. public static void autoFilter(HSSFSheet sh, int topLeftRow, int topLeftCol, Object filterValue){
  559. autoFilter(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  560. new CellReference(topLeftRow, topLeftCol)), filterValue);
  561. }
  562. public static void autoFilter(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, Object filterValue){
  563. autoFilter(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  564. new CellReference(botRightRow, botRightCol)), filterValue);
  565. }
  566. public static void autoFilter(HSSFSheet sh, CellReference topLeft, CellReference botRight, Object filterValue){
  567. autoFilter(sh, new AreaReference(topLeft, botRight), filterValue);
  568. }
  569. public static void autoFilter(HSSFSheet sh, String strAreaRef, Object filterValue){
  570. autoFilter(sh, new AreaReference(strAreaRef), filterValue);
  571. }
  572. public static void autoFilter(HSSFSheet sh, CellRangeAddress cellsRef, Object filterValue){
  573. autoFilter(sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  574. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), filterValue);
  575. }
  576. public static void autoFilter(HSSFSheet sh, AreaReference areaRef, Object filterValue){
  577. if (areaRef.getFirstCell().getCol() != areaRef.getLastCell().getCol()) return;
  578. for(CellReference cellRef:areaRef.getAllReferencedCells()){
  579. if (filterValue != null){
  580. HSSFCell cell = getCell(sh, cellRef.getRow(), cellRef.getCol());
  581. Object cellValue = getCellValue(cell);
  582. if (cellValue == null || !getCellValue(cell).equals(filterValue))
  583. getRow(sh, cellRef.getRow()).setZeroHeight(true);
  584. }
  585. else getRow(sh, cellRef.getRow()).setZeroHeight(false);
  586. }
  587. }
  588. public static void replaceRows(HSSFSheet sh, int firstRow, int lastRow, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  589. //System.out.println("replaceRows... firstRow = " + firstRow + ", lastRow = " + lastRow + ", valueSearch = " + valueSearch + ", valueReplace = " + valueReplace);
  590. replace(sh, new AreaReference(new CellReference(firstRow, 0),
  591. new CellReference(lastRow, xlMaxNumCol)), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  592. }
  593. public static void replace(HSSFSheet sh, int row, int col, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  594. replace(sh, new AreaReference(new CellReference(row, col),
  595. new CellReference(row, col)), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  596. }
  597. public static void replace(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  598. replace(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  599. new CellReference(botRightRow, botRightCol)), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  600. }
  601. public static void replace(HSSFSheet sh, CellReference topLeft, CellReference botRight, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  602. replace(sh, new AreaReference(topLeft, botRight), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  603. }
  604. public static void replace(HSSFSheet sh, CellRangeAddress cellsRef, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  605. replace(sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  606. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  607. }
  608. public static void replace(HSSFSheet sh, String strAreaRef, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  609. replace(sh, new AreaReference(strAreaRef), valueSearch, valueReplace, lookIn, lookAt, searchDirection);
  610. }
  611. public static void replace(HSSFSheet sh, AreaReference areaRef, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  612. findInArea(sh, areaRef, valueSearch, valueReplace, lookIn, lookAt, searchDirection, false, true);
  613. }
  614. public static List<HSSFCell> findAll(HSSFSheet sh, int topLeftRow, int topLeftCol, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  615. return findAll(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  616. new CellReference(topLeftRow, topLeftCol)), valueSearch, lookIn, lookAt, searchDirection);
  617. }
  618. public static List<HSSFCell> findAll(HSSFSheet sh, CellRangeAddress cellsRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  619. return findAll(sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  620. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), valueSearch, lookIn, lookAt, searchDirection);
  621. }
  622. public static List<HSSFCell> colsFindAll(HSSFSheet sh, int firstCol, int lastCol, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  623. return findAll(sh, sh.getFirstRowNum(), firstCol, sh.getLastRowNum(), lastCol, valueSearch, lookIn, lookAt, searchDirection);
  624. }
  625. public static List<HSSFCell> findAll(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  626. return findAll(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  627. new CellReference(botRightRow, botRightCol)), valueSearch, lookIn, lookAt, searchDirection);
  628. }
  629. public static List<HSSFCell> findAll(HSSFSheet sh, CellReference topLeft, CellReference botRight, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  630. return findAll(sh, new AreaReference(topLeft, botRight), valueSearch, lookIn, lookAt, searchDirection);
  631. }
  632. public static List<HSSFCell> findAll(HSSFSheet sh, String strAreaRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  633. return findAll(sh, new AreaReference(strAreaRef), valueSearch, lookIn, lookAt, searchDirection);
  634. }
  635. public static List<HSSFCell> findAll(HSSFSheet sh, AreaReference areaRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  636. return findInArea(sh, areaRef, valueSearch, null, lookIn, lookAt, searchDirection, false, false);
  637. }
  638. public static HSSFCell find(HSSFSheet sh, int topLeftRow, int topLeftCol, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  639. return find(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  640. new CellReference(topLeftRow, topLeftCol)), valueSearch, lookIn, lookAt, searchDirection);
  641. }
  642. public static HSSFCell find(HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  643. return find(sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  644. new CellReference(botRightRow, botRightCol)), valueSearch, lookIn, lookAt, searchDirection);
  645. }
  646. public static HSSFCell find(HSSFSheet sh, CellReference topLeft, CellReference botRight, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  647. return find(sh, new AreaReference(topLeft, botRight), valueSearch, lookIn, lookAt, searchDirection);
  648. }
  649. public static HSSFCell find(HSSFSheet sh, CellRangeAddress cellsRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  650. return find(sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  651. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())),
  652. valueSearch, lookIn, lookAt, searchDirection);
  653. }
  654. public static HSSFCell find(HSSFSheet sh, String strAreaRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  655. return find(sh, new AreaReference(strAreaRef), valueSearch, lookIn, lookAt, searchDirection);
  656. }
  657. public static HSSFCell find(HSSFSheet sh, AreaReference areaRef, Object valueSearch, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection){
  658. List<HSSFCell> list = findInArea(sh, areaRef, valueSearch, null, lookIn, lookAt, searchDirection, true, false);
  659. if (list.size() > 0) return list.get(0);
  660. else return null;
  661. }
  662. private static List<HSSFCell> findInArea(HSSFSheet sh,
  663. AreaReference areaRef, Object valueSearch, Object valueReplace, byte lookIn, XlLookAt lookAt, XlSearchDirection searchDirection, boolean isFirst, boolean isReplace){
  664. List<HSSFCell> list = new ArrayList<HSSFCell>();
  665. String strSearchValue = null, strReplaceValue = null;
  666. Date dateSearchValue = null, dateReplaceValue = null;
  667. Boolean boolSearchValue = null, boolReplaceValue = null;
  668. Number numSearchValue = null, numReplaceValue = null;
  669. Pattern p = null;
  670. if(valueSearch instanceof Number){
  671. numSearchValue = (Number)valueSearch;
  672. if (isReplace && valueReplace != null) numReplaceValue = (Number)valueReplace;
  673. }else if(valueSearch instanceof Boolean){
  674. boolSearchValue = (Boolean)valueSearch;
  675. if (isReplace && valueReplace != null) boolReplaceValue = (Boolean)valueReplace;
  676. }else if(valueSearch instanceof Date){
  677. dateSearchValue = (Date)valueSearch;
  678. if (isReplace && valueReplace != null) dateReplaceValue = (Date)valueReplace;
  679. }else {
  680. strSearchValue = normalizeStringForRegex(valueSearch.toString());
  681. if (lookAt == XlLookAt.xlWhole){
  682. p = Pattern.compile("\\b"+strSearchValue+"\\b");
  683. strSearchValue = p.pattern();
  684. }
  685. if (isReplace && valueReplace != null) strReplaceValue = valueReplace.toString();
  686. }
  687. int realFirstRow = areaRef.getFirstCell().getRow() > sh.getFirstRowNum() ?areaRef.getFirstCell().getRow():sh.getFirstRowNum();
  688. int realLastRow = areaRef.getLastCell().getRow() < sh.getLastRowNum() ?areaRef.getLastCell().getRow():sh.getLastRowNum();
  689. int realFirstCol = areaRef.getFirstCell().getCol() > sh.getLeftCol() ?areaRef.getFirstCell().getCol():sh.getLeftCol();
  690. int realRow =0;
  691. for(int iRow = realFirstRow; iRow <= realLastRow; iRow++){
  692. realRow = searchDirection == XlSearchDirection.xlNext ? iRow: realLastRow+(realFirstRow-iRow);
  693. HSSFRow row = sh.getRow(realRow);
  694. if (row != null){
  695. int realCol =0;
  696. for(int iCol = realFirstCol; iCol <= areaRef.getLastCell().getCol(); iCol++){
  697. realCol = searchDirection == XlSearchDirection.xlNext ? iCol: areaRef.getLastCell().getCol()+(realFirstCol-iCol);
  698. HSSFCell cell = row.getCell(realCol);
  699. if (cell != null){
  700. if (lookIn == xlValues && cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA){
  701. Object value = getCellValue(cell);
  702. if (cell != null && value != null){
  703. if(value instanceof Number){
  704. Number numValue = (Number)value;
  705. if (numSearchValue != null && numSearchValue.equals(numValue)){
  706. list.add(cell);
  707. if (isReplace) cell.setCellValue(numReplaceValue.doubleValue());
  708. if (isFirst && list.size() > 0) return list;
  709. }
  710. }else if(value instanceof Boolean){
  711. Boolean boolValue = (Boolean)value;
  712. if (boolSearchValue != null && boolSearchValue.compareTo(boolValue) == 0){
  713. list.add(cell);
  714. if (isReplace) cell.setCellValue(boolReplaceValue);
  715. if (isFirst && list.size() > 0) return list;
  716. }
  717. }else if(value instanceof Date){
  718. Date dateValue = (Date)value;
  719. if (dateSearchValue != null && dateValue.compareTo(dateSearchValue) == 0){
  720. list.add(cell);
  721. if (isReplace) cell.setCellValue(dateReplaceValue);
  722. if (isFirst && list.size() > 0) return list;
  723. }
  724. }else {
  725. String strValue = value.toString();
  726. if (strSearchValue != null){
  727. if (isReplace){
  728. String res = strValue.replaceAll(strSearchValue, strReplaceValue);
  729. cell.setCellValue(new HSSFRichTextString(res));
  730. if (!res.equals(strValue)) list.add(cell);
  731. }
  732. else {
  733. if (p != null && p.matcher(strValue).find())list.add(cell);
  734. else if (strValue.indexOf(strSearchValue)>=0) list.add(cell);
  735. }
  736. if (isFirst && list.size() > 0) return list;
  737. }
  738. }
  739. }
  740. }else if(lookIn == xlFormulas && strSearchValue != null && cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  741. String formula = cell.getCellFormula();
  742. if (formula != null){
  743. if(isReplace){
  744. String res = formula.replaceAll(strSearchValue, strReplaceValue);
  745. cell.setCellFormula(res);
  746. if (!res.equals(formula)) list.add(cell);
  747. }
  748. else {
  749. if (p != null && p.matcher(formula).find())list.add(cell);
  750. else if (formula.indexOf(strSearchValue)>=0) list.add(cell);
  751. }
  752. if (isFirst && list.size() > 0) return list;
  753. }
  754. }else if(lookIn == xlComments && strSearchValue != null){
  755. HSSFComment comment = cell.getCellComment();
  756. if (comment != null){
  757. HSSFRichTextString richTextString = comment.getString();
  758. if (richTextString != null){
  759. String textComment = richTextString.getString();
  760. if (textComment != null){
  761. if(isReplace){
  762. String res = textComment.replaceAll(strSearchValue, strReplaceValue);
  763. comment.setString(new HSSFRichTextString(res));
  764. if (!res.equals(textComment)) list.add(cell);
  765. }else{
  766. if (p != null && p.matcher(textComment).find())list.add(cell);
  767. else if (textComment.indexOf(strSearchValue)>=0) list.add(cell);
  768. }
  769. if (isFirst && list.size() > 0) return list;
  770. }
  771. }
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. return list;
  779. }
  780. public static int findMarkInColumn(HSSFSheet sh, String markValue, int columnIndex, int startRow){
  781. Double numericMarkValue = CastUtils.doubleValue(markValue, null);
  782. Iterator rowIt = sh.rowIterator();
  783. while(rowIt.hasNext()){
  784. HSSFRow row = (HSSFRow)rowIt.next();
  785. if(row != null){
  786. if(row.getRowNum() >= startRow){
  787. HSSFCell cell = row.getCell(columnIndex);
  788. if(cell != null){
  789. switch(cell.getCellType()){
  790. case HSSFCell.CELL_TYPE_STRING:
  791. HSSFRichTextString rich = cell.getRichStringCellValue();
  792. if(markValue != null){
  793. if((rich != null) && markValue.equals(rich.getString())){
  794. return row.getRowNum();
  795. }
  796. } else {
  797. if(rich == null){
  798. return row.getRowNum();
  799. }
  800. }
  801. break;
  802. case HSSFCell.CELL_TYPE_NUMERIC:
  803. if(numericMarkValue != null){
  804. if(numericMarkValue.equals(cell.getNumericCellValue())){
  805. return row.getRowNum();
  806. }
  807. } else {}
  808. break;
  809. }
  810. }
  811. }
  812. } else{
  813. }
  814. }
  815. return -1;
  816. }
  817. public static int findUsedCellInColumn(HSSFSheet sh, int columnIndex, int startRow){
  818. Iterator rowIt = sh.rowIterator();
  819. while(rowIt.hasNext()){
  820. HSSFRow row = (HSSFRow)rowIt.next();
  821. if(row != null){
  822. if(row.getRowNum() >= startRow){
  823. HSSFCell cell = row.getCell(columnIndex);
  824. if(cell != null){
  825. switch(cell.getCellType()){
  826. case HSSFCell.CELL_TYPE_STRING:
  827. HSSFRichTextString rich = cell.getRichStringCellValue();
  828. if(rich != null) return row.getRowNum();
  829. break;
  830. case HSSFCell.CELL_TYPE_NUMERIC:
  831. return row.getRowNum();
  832. }
  833. }
  834. }
  835. }
  836. }
  837. return -1;
  838. }
  839. public static String xlc(int colIndex){
  840. StringBuilder sb = new StringBuilder(2);
  841. int base = 26;
  842. if(colIndex <= 0) return "";
  843. int v = colIndex-1;
  844. while(v >= 0){
  845. int r = v / base;
  846. int c = v - r * base;
  847. sb.insert(0, (char)((int)'A' + c));
  848. v = r - 1;
  849. if(v < 0) break;
  850. }
  851. return sb.toString();
  852. }
  853. public static CellRangeAddressList getEntireColumn(CellRangeAddressList cellsRefs){
  854. Set<Integer> set = new HashSet<Integer>();
  855. for(int i=0; i<cellsRefs.countRanges(); i++){
  856. CellRangeAddress crA = cellsRefs.getCellRangeAddress(i);
  857. for(int row =crA.getFirstRow(); row<=crA.getLastRow(); row++)
  858. set.add(new Integer(row));
  859. }
  860. Iterator it = set.iterator();
  861. int count =0;
  862. int prevIndexCol =0, indexCol =0, firstIndexCol = -1;
  863. CellRangeAddress crA;
  864. CellRangeAddressList listCrA = new CellRangeAddressList();
  865. while(it.hasNext()){
  866. indexCol = (Integer)it.next();
  867. if (count > 0 && indexCol - prevIndexCol > 1){
  868. crA = new CellRangeAddress(0, xlMaxNumRow-1, firstIndexCol, prevIndexCol);
  869. listCrA.addCellRangeAddress(crA);
  870. firstIndexCol = indexCol;
  871. }else if (count == 0) firstIndexCol = indexCol;
  872. prevIndexCol = indexCol;
  873. count++;
  874. }
  875. if (firstIndexCol >= 0){
  876. crA = new CellRangeAddress(0, xlMaxNumRow-1, firstIndexCol, prevIndexCol);
  877. listCrA.addCellRangeAddress(crA);
  878. }
  879. return listCrA.countRanges() > 0?listCrA:null;
  880. }
  881. public static CellRangeAddressList getEntireRow(CellRangeAddressList cellsRefs){
  882. Set<Integer> set = new HashSet<Integer>();
  883. for(int i=0; i<cellsRefs.countRanges(); i++){
  884. CellRangeAddress crA = cellsRefs.getCellRangeAddress(i);
  885. for(int row =crA.getFirstRow(); row<=crA.getLastRow(); row++){
  886. set.add(new Integer(row));
  887. }
  888. }
  889. Object[] arr = set.toArray();
  890. Arrays.sort(arr);
  891. int count =0;
  892. int prevIndexRow = 0, firstIndexRow = -1;
  893. CellRangeAddress crA;
  894. CellRangeAddressList listCrA = new CellRangeAddressList();
  895. for(Object indexObj:arr){
  896. int indexRow = (Integer)indexObj;
  897. if (count > 0 && indexRow - prevIndexRow > 1){
  898. crA = new CellRangeAddress(firstIndexRow, prevIndexRow, 0, xlMaxNumCol-1);
  899. listCrA.addCellRangeAddress(crA);
  900. firstIndexRow = indexRow;
  901. }else if (count == 0) firstIndexRow = indexRow;
  902. prevIndexRow = indexRow;
  903. count++;
  904. }
  905. if (firstIndexRow >= 0){
  906. crA = new CellRangeAddress(firstIndexRow, prevIndexRow, 0, xlMaxNumCol-1);
  907. listCrA.addCellRangeAddress(crA);
  908. }
  909. return listCrA.countRanges() > 0?listCrA:null;
  910. }
  911. public static CellRangeAddress mergeArea(HSSFSheet sh, CellReference cellRef){
  912. for(int i = 0; i <sh.getNumMergedRegions(); i++){
  913. CellRangeAddress rangeRef = sh.getMergedRegion(i);
  914. if (cellRef.getCol() >= rangeRef.getFirstColumn() && cellRef.getCol() <= rangeRef.getLastColumn() &&
  915. cellRef.getRow() >= rangeRef.getFirstRow() && cellRef.getRow() <= rangeRef.getLastRow()){
  916. return rangeRef;
  917. }
  918. }
  919. return new CellRangeAddress(cellRef.getRow(), cellRef.getCol(), cellRef.getRow(), cellRef.getCol());
  920. }
  921. public static ExcelBuffer copy (HSSFSheet sh, int topLeftRow, int topLeftCol){
  922. return copy (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  923. new CellReference(topLeftRow, topLeftCol)));
  924. }
  925. public static ExcelBuffer copy (HSSFSheet sh, CellRangeAddress cellsRef){
  926. return copy (sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  927. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())));
  928. }
  929. public static ExcelBuffer copyRows (HSSFSheet sh, int topRow, int botRow){
  930. return copy (sh, new AreaReference(new CellReference(topRow, 0),
  931. new CellReference(botRow, xlMaxNumCol-1)));
  932. }
  933. public static ExcelBuffer copy (HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol){
  934. return copy (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  935. new CellReference(botRightRow, botRightCol)));
  936. }
  937. public static ExcelBuffer copy (HSSFSheet sh, String areaRef){
  938. return copy (sh, new AreaReference(areaRef));
  939. }
  940. public static ExcelBuffer copy (HSSFSheet sh, CellReference topLeft, CellReference botRight){
  941. return copy (sh, new AreaReference(topLeft, botRight));
  942. }
  943. public static ExcelBuffer copy (HSSFSheet sh, AreaReference areaRef){
  944. Map<String, ExcelCell> mapCell = new HashMap<String, ExcelCell>();
  945. int offsetRow = areaRef.getFirstCell().getRow();
  946. int offsetCol = areaRef.getFirstCell().getCol();
  947. CellReference[] celRefs = areaRef.getAllReferencedCells();
  948. for(CellReference celRef:celRefs){
  949. String key = (celRef.getRow()-offsetRow)+"_"+(celRef.getCol()-offsetCol);
  950. mapCell.put(key, new ExcelCell(getCell(sh, celRef.getRow(), celRef.getCol())));
  951. }
  952. return new ExcelBuffer(sh, areaRef, mapCell);
  953. }
  954. public static void paste (HSSFSheet sh, int topLeftRow, int topLeftCol, ExcelBuffer buffer){
  955. paste (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  956. new CellReference(topLeftRow, topLeftCol)), buffer, xlAll);
  957. }
  958. public static void paste (HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, ExcelBuffer buffer){
  959. paste (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  960. new CellReference(botRightRow, botRightCol)), buffer, xlAll);
  961. }
  962. public static void paste(HSSFSheet sh, CellRangeAddress cellsRef, ExcelBuffer buffer ){
  963. paste (sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  964. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), buffer, xlAll);
  965. }
  966. public static void paste (HSSFSheet sh, CellReference topLeft, CellReference botRight, ExcelBuffer buffer){
  967. paste (sh, new AreaReference(topLeft, botRight), buffer, xlAll);
  968. }
  969. public static void paste (HSSFSheet sh, String areaRef, ExcelBuffer buffer){
  970. paste (sh, new AreaReference (areaRef), buffer, xlAll);
  971. }
  972. public static void paste (HSSFSheet sh, AreaReference areaRef, ExcelBuffer buffer){
  973. paste (sh, areaRef, buffer, xlAll);
  974. }
  975. public static void pasteRows (HSSFSheet sh, int topRow, int botRow, ExcelBuffer buffer, byte typePaste){
  976. paste (sh, new AreaReference(new CellReference(topRow, 0),
  977. new CellReference(botRow, xlMaxNumCol-1)), buffer, typePaste);
  978. }
  979. public static void paste (HSSFSheet sh, int topLeftRow, int topLeftCol, ExcelBuffer buffer, byte typePaste){
  980. paste (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  981. new CellReference(topLeftRow, topLeftCol)), buffer, typePaste);
  982. }
  983. public static void paste (HSSFSheet sh, int topLeftRow, int topLeftCol, int botRightRow, int botRightCol, ExcelBuffer buffer, byte typePaste){
  984. paste (sh, new AreaReference(new CellReference(topLeftRow, topLeftCol),
  985. new CellReference(botRightRow, botRightCol)), buffer, typePaste);
  986. }
  987. public static void paste(HSSFSheet sh, CellRangeAddress cellsRef, ExcelBuffer buffer, byte typePaste){
  988. paste (sh, new AreaReference(new CellReference(cellsRef.getFirstRow(), cellsRef.getFirstColumn()),
  989. new CellReference(cellsRef.getLastRow(), cellsRef.getLastColumn())), buffer, typePaste);
  990. }
  991. public static void paste (HSSFSheet sh, CellReference topLeft, CellReference botRight, ExcelBuffer buffer, byte typePaste){
  992. paste (sh, new AreaReference(topLeft, botRight), buffer, typePaste);
  993. }
  994. public static void paste (HSSFSheet sh, String areaRef, ExcelBuffer buffer, byte typePaste){
  995. paste (sh, new AreaReference (areaRef), buffer, typePaste);
  996. }
  997. public static void paste (HSSFSheet sh, AreaReference areaRef, ExcelBuffer buffer, byte typePaste){
  998. int copyRow1 = buffer.getAreaRef().getFirstCell().getRow();
  999. int copyCol1 = buffer.getAreaRef().getFirstCell().getCol();
  1000. int copyRow2 = buffer.getAreaRef().getLastCell().getRow();
  1001. int copyCol2 = buffer.getAreaRef().getLastCell().getCol();
  1002. int deltaCopyRow = copyRow2 - copyRow1+1;
  1003. int deltaCopyCol = copyCol2 - copyCol1+1;
  1004. int pasteRow1 = areaRef.getFirstCell().getRow();
  1005. int pasteCol1 = areaRef.getFirstCell().getCol();
  1006. int pasteRow2 = areaRef.getLastCell().getRow();
  1007. int pasteCol2 = areaRef.getLastCell().getCol();
  1008. int deltaPasteRow = pasteRow2 - pasteRow1+1;
  1009. int deltaPasteCol = pasteCol2 - pasteCol1+1;
  1010. int nRow = 1;
  1011. int nCol = 1;
  1012. if(deltaPasteRow%deltaCopyRow==0 && deltaPasteCol%deltaCopyCol==0){
  1013. int nRow1 = deltaPasteRow/deltaCopyRow;
  1014. int nCol1 = deltaPasteCol/deltaCopyCol;
  1015. if (nRow1 != 0) nRow = nRow1;
  1016. if (nCol1 != 0) nCol = nCol1;
  1017. }
  1018. for(int row = 0; row < deltaCopyRow*nRow; row++){
  1019. int indexRow = row % deltaCopyRow;
  1020. HSSFRow copyRow = buffer.getSrcSheet().getRow(copyRow1+indexRow);
  1021. HSSFRow pasteRow = getRow(sh, pasteRow1 + row);
  1022. int offsetRow = pasteRow.getRowNum()-copyRow.getRowNum();
  1023. for(int col = 0; col < deltaCopyCol*nCol; col++){
  1024. int indexCol = col % deltaCopyCol;
  1025. int pasteColumn = pasteCol1 + col;
  1026. int copyColumn = copyCol1+indexCol;
  1027. HSSFCell cell = getCell(pasteRow, pasteColumn);
  1028. buffer.getListCell().get(indexRow+"_"+indexCol).pasteSpecial(cell, typePaste,
  1029. offsetRow, cell.getColumnIndex()-copyColumn);
  1030. if(row == 0 && (typePaste == xlAll || typePaste == xlColumnWidths || typePaste == xlFormats || typePaste == xlFormulasAndNumberFormats)){
  1031. sh.setColumnWidth(pasteColumn, buffer.getSrcSheet().getColumnWidth(copyColumn));
  1032. if (buffer.getSrcSheet().isColumnHidden(copyColumn)) sh.setColumnHidden(pasteColumn, true);
  1033. }
  1034. }
  1035. if (copyRow != null){
  1036. /*
  1037. System.out.println("setRowHeight at line #" + (pasteRow.getRowNum() + 1) + " from line #" + (copyRow.getRowNum() + 1));
  1038. if (copyRow.getZeroHeight()){
  1039. System.out.println("copyRow.getZeroHeight() = " + copyRow.getZeroHeight());
  1040. pasteRow.setZeroHeight(true);
  1041. }else{
  1042. pasteRow.setHeight(copyRow.getHeight());
  1043. }
  1044. */
  1045. if (!copyRow.getZeroHeight()) pasteRow.setHeight(copyRow.getHeight());
  1046. }
  1047. }
  1048. if(typePaste == xlAll || typePaste == xlFormats || typePaste == xlFormulasAndNumberFormats){
  1049. for(int indexMergeRegion=0; indexMergeRegion< buffer.getSrcSheet().getNumMergedRegions(); indexMergeRegion++){
  1050. CellRangeAddress cra = buffer.getSrcSheet().getMergedRegion(indexMergeRegion);
  1051. if (cra.getFirstRow() >= copyRow1 && cra.getLastRow() <= copyRow2
  1052. && cra.getFirstColumn() >= copyCol1 && cra.getLastColumn() <= copyCol2){
  1053. int offsetRow = cra.getFirstRow()-copyRow1;
  1054. int offsetCol = cra.getFirstColumn()-copyCol1;
  1055. int countRowMergeRegion = cra.getLastRow()-cra.getFirstRow();
  1056. int countColMergeRegion = cra.getLastColumn()-cra.getFirstColumn();
  1057. for(int i =0; i < nRow; i++){
  1058. int indexBegRowMergeRegion = pasteRow1 + i + offsetRow;
  1059. int indexEndRowMergeRegion = indexBegRowMergeRegion+countRowMergeRegion;
  1060. //System.out.println("deltaCopyCol*nCol "+(nCol));
  1061. for(int j =0; j < nCol; j++){
  1062. int indexBegColMergeRegion = pasteCol1 + j + offsetCol;
  1063. CellRangeAddress pasteCRA =
  1064. new CellRangeAddress(indexBegRowMergeRegion,
  1065. indexEndRowMergeRegion,
  1066. indexBegColMergeRegion,
  1067. indexBegColMergeRegion+countColMergeRegion);
  1068. sh.addMergedRegion(pasteCRA);
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. }
  1075. public static void hiddenRows(HSSFSheet sh, CellRangeAddressList list, boolean hide){
  1076. if (list != null){
  1077. for(int jj=0; jj<list.countRanges(); jj++){
  1078. CellRangeAddress cra = list.getCellRangeAddress(jj);
  1079. for(int row = cra.getFirstRow(); row <= cra.getLastRow(); row++)
  1080. ExcelUtils.getRow(sh, row).setZeroHeight(hide);
  1081. }
  1082. }
  1083. }
  1084. public static void hiddenRows(HSSFSheet sh, AreaReference area, boolean hide){
  1085. if (area != null)
  1086. for(int row = area.getFirstCell().getRow(); row <= area.getLastCell().getRow(); row++)
  1087. ExcelUtils.getRow(sh, row).setZeroHeight(hide);
  1088. }
  1089. public static void setRowHeight(HSSFSheet sh, AreaReference area, short height){
  1090. for(int row = area.getFirstCell().getRow(); row <= area.getLastCell().getRow(); row++)
  1091. getRow(sh, row).setHeight(height);
  1092. }
  1093. public static Short getRowHeight(HSSFSheet sh, AreaReference area){
  1094. Short height = null;
  1095. for(int row = area.getFirstCell().getRow(); row <= area.getLastCell().getRow(); row++){
  1096. HSSFRow hSSFRow = getRow(sh, row);
  1097. if (row == area.getFirstCell().getRow()) height = hSSFRow.getHeight();
  1098. if (height != hSSFRow.getHeight()) return null;
  1099. }
  1100. return height;
  1101. }
  1102. public static void insertRows(HSSFSheet sh, int beginIndex, int numRow){
  1103. sh.shiftRows(beginIndex, sh.getLastRowNum(), numRow);
  1104. }
  1105. public static HSSFName getNamedRange(HSSFWorkbook wb, String name){
  1106. int n = wb.getNumberOfNames();
  1107. if(name==null){
  1108. for(int i = 0; i < n; i++){
  1109. HSSFName iName = wb.getNameAt(i);
  1110. if((iName != null) && (iName.getNameName() == null)) return iName;
  1111. }
  1112. }else{
  1113. for(int i = 0; i < n; i++){
  1114. HSSFName iName = wb.getNameAt(i);
  1115. if((iName != null) && (iName.getNameName() != null) && iName.getNameName().equals(name)) return iName;
  1116. }
  1117. }
  1118. return null;
  1119. }
  1120. public static void deleteRow(HSSFSheet sh, int indexRow){
  1121. HSSFRow hSSFRow = getRow(sh, indexRow);
  1122. if (hSSFRow != null) sh.removeRow(hSSFRow);
  1123. }
  1124. public static HSSFRow clearRow(HSSFSheet sh, int indexRow){
  1125. HSSFRow hSSFRow = getRow(sh, indexRow);
  1126. if (hSSFRow != null) {
  1127. Iterator it = hSSFRow.cellIterator();
  1128. while(it.hasNext())
  1129. hSSFRow.removeCell((HSSFCell)it.next());
  1130. }
  1131. return hSSFRow;
  1132. }
  1133. public static void breakDownPrintedPage(HSSFSheet sh) throws JUniPrintException{
  1134. HSSFPrintSetup ps = sh.getPrintSetup();
  1135. float[]sizePage = PrintPagesFormat.get(ps.getPaperSize());
  1136. if (sizePage == null) throw new JUniPrintException("Неизвестный формат печатный страницы!");
  1137. float baseSizePage = 0;
  1138. if (ps.getLandscape()) baseSizePage = sizePage[0];
  1139. else baseSizePage = sizePage[1];
  1140. float scale = ps.getScale() / 100;
  1141. double l = baseSizePage -(((ps.getFooterMargin()+ps.getHeaderMargin())*Factotr_MM_Inches)+50);
  1142. double currSizePage = 0;
  1143. for(int indexRow =0; indexRow <=sh.getLastRowNum(); indexRow++ ){
  1144. HSSFRow row = sh.getRow(indexRow);
  1145. if (row != null && !row.getZeroHeight()){
  1146. currSizePage += row.getHeightInPoints()*Factotr_MM_Points*scale;
  1147. }
  1148. if (currSizePage >= l || sh.isRowBroken(indexRow)){
  1149. currSizePage = 0;
  1150. if (!sh.isRowBroken(indexRow)) sh.setRowBreak(indexRow);
  1151. }
  1152. }
  1153. }
  1154. public static String normalizeStringForRegex(String arg){
  1155. return arg.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)").replaceAll("\\$", "\\\\\\$");
  1156. }
  1157. public static AreaReference range(HSSFWorkbook wb, String nameRange){
  1158. return range(wb, nameRange, null, null);
  1159. }
  1160. public static AreaReference range(HSSFWorkbook wb, String nameRange, Map<String, Map<String, HSSFName>> mapWbNames, String[] sheetNames){
  1161. HSSFName name = sheetNames == null ? getNamedRange(wb, nameRange):getNamedRangeInSheets(mapWbNames, nameRange, sheetNames);
  1162. return getReferanceNameRange(name);
  1163. }
  1164. public static HSSFCell singleRangeToCell(HSSFWorkbook wb, String nameRange, Map<String, Map<String, HSSFName>> mapWbNames, String[] sheetNames){
  1165. AreaReference ref = range(wb, nameRange, mapWbNames, sheetNames);
  1166. if (ref.isSingleCell()){
  1167. String shName = ref.getFirstCell().getSheetName();
  1168. return getCell(wb.getSheet(shName), ref.getFirstCell().getRow(), ref.getFirstCell().getCol());
  1169. }else return null;
  1170. }
  1171. public static HSSFCell singleRangeToCell(HSSFWorkbook wb, String nameRange){
  1172. return singleRangeToCell(wb, nameRange, null, null);
  1173. }
  1174. public static Object singleRangeToCellValue(HSSFWorkbook wb, String nameRange){
  1175. HSSFCell cell = singleRangeToCell(wb, nameRange, null, null);
  1176. if (cell != null) return getCellValue(cell);
  1177. else return null;
  1178. }
  1179. public static Object singleRangeToCellValue(HSSFWorkbook wb, String nameRange, Map<String, Map<String, HSSFName>> mapWbNames, String[] sheetNames){
  1180. HSSFCell cell = singleRangeToCell(wb, nameRange, mapWbNames, sheetNames);
  1181. if (cell != null) return getCellValue(cell);
  1182. else return null;
  1183. }
  1184. public static void main(String[] args) throws IOException {
  1185. String s = "D3+C3+SUMM(A2:A3)";
  1186. String s1 = "";
  1187. Pattern p = Pattern.compile("\\b([A-Z][A-V]?)(\\d+)\\b");
  1188. Matcher m = p.matcher(s);
  1189. List<ExtCellReference> list = new ArrayList<ExtCellReference>();
  1190. int deltaPos = 0;
  1191. s1 = s;
  1192. while(m.find()){
  1193. int start = m.start(0);
  1194. int end = m.end(0);
  1195. list.add(new ExtCellReference(m.group(0), m.start(0), m.end(0)));
  1196. s1 = s1.substring(0, start-deltaPos)+"#"+s1.substring(end-deltaPos, s1.length());
  1197. deltaPos += (end-start)-1;
  1198. }
  1199. String[]ss = s1.split("#");
  1200. String res2 = "";
  1201. int count = -1;
  1202. for(String path:ss){
  1203. res2 += path+(++count<list.size()?list.get(count).getUpdateCellReference(10, 0).formatAsString():"");
  1204. }
  1205. String s2 = "\"Всего по $ профессии \"&\"un(D:D)\"";
  1206. System.out.println(s2.replaceAll(normalizeStringForRegex("un(D:D)"), "Уборщица"));
  1207. /*
  1208. for(ExtCellReference el:list){
  1209. //el.
  1210. res2 += ss[count++]+el.getUpdateCellReference(10, 0).formatAsString();
  1211. }
  1212. */
  1213. System.out.println(res2);
  1214. s = "#";
  1215. System.out.println(s.split("#").length);
  1216. }
  1217. }