PageRenderTime 77ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main/java/org/comsoft/juniprint/JUniPrint.java

https://bitbucket.org/openicar/juniprint
Java | 2095 lines | 1728 code | 128 blank | 239 comment | 613 complexity | e9487002cf69dbd9246766c01c968b73 MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  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;
  21. import java.util.ArrayList;
  22. import java.util.Calendar;
  23. import java.util.Date;
  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import org.apache.poi.hssf.record.formula.functions.FreeRefFunction;
  29. import org.apache.poi.hssf.record.formula.udf.DefaultUDFFinder;
  30. import org.apache.poi.hssf.usermodel.HSSFCell;
  31. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  32. import org.apache.poi.hssf.usermodel.HSSFComment;
  33. import org.apache.poi.hssf.usermodel.HSSFFont;
  34. import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
  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.HSSFShape;
  40. import org.apache.poi.hssf.usermodel.HSSFSheet;
  41. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  42. import org.apache.poi.ss.util.AreaReference;
  43. import org.apache.poi.ss.util.CellRangeAddress;
  44. import org.apache.poi.ss.util.CellRangeAddressList;
  45. import org.apache.poi.ss.util.CellReference;
  46. import org.comsoft.juniprint.userfunction.FML;
  47. import org.comsoft.juniprint.userfunction.FMLR;
  48. import org.comsoft.juniprint.userfunction.Nmb_Prop;
  49. import org.comsoft.juniprint.userfunction.Sum_Prop;
  50. import org.comsoft.juniprint.utils.ExcelBuffer;
  51. import org.comsoft.juniprint.utils.ExcelUtils;
  52. public class JUniPrint {
  53. private static final Integer dimensions = 10; //размерность вектора
  54. private static final Integer dimensions2 = 20; //размерность вектора
  55. private static final Short xlSheetNumRow = 20; //число строк на листе
  56. private static final String RANGE_DATABEG = "DataBeg"; //
  57. private static final String RANGE_CUSING = "cusing";
  58. private static final String RANGE_ContentBegCol = "ContentBegCol";
  59. private static final String RANGE_ContentBegColRowHead = "ContentBegColRowHead";
  60. private static final String RANGE_DataRangeE = "DataRangeE"; //
  61. private static final String RANGE_DataRangeB = "DataRangeB"; //
  62. private static final String RANGE_DataPageE = "DataPageE";
  63. private HSSFName nameDataBeg;
  64. private HSSFName nameDataRangeE;
  65. private HSSFName nameDataRangeB;
  66. private HSSFName nameDataPageE;
  67. private static final String RESWORD_Series = "Series"; //
  68. private static final String RESWORD_PageFromDetail = "PageFromDetail"; //
  69. private static final String RESWORD_HPageBreak = "HPageBreak"; //
  70. private static final String RESWORD_AutoHeight = "AutoHeight"; //
  71. private static final String RESWORD_MultiHide = "MultiHide"; //
  72. private static final String RESWORD_ModSer = "ModSer"; //
  73. private static final String RESWORD_Group = "Group"; //
  74. private static final String RESWORD_GroupHide = "GroupHide"; //
  75. private static final String RESWORD_Uniq = "uniq"; //
  76. public static final Short FACTOR_PIXEL_TO_EXCEL = 52;
  77. private HSSFWorkbook wb;
  78. private HSSFFormulaEvaluator evaluator;
  79. Map<String, Map<String, HSSFName>> namesMap = null;
  80. String[] sheets = null;
  81. private HSSFFont fontWhiteColor;
  82. private HSSFCellStyle[] arrCellStyleTextWhiteColor;
  83. private boolean useSpecialSheets;
  84. private boolean useGeneral;
  85. private boolean hideDetailRows;
  86. //============================= Переменные для ОБРАЗЦА
  87. private int lastCol; //Колонка реально последняя
  88. private int modelRowE, modelColE; //ОБРАЗЕЦ номер послед.строки, колонки
  89. private int headPrimeRowB, headPrimeRowE;
  90. private String headPrimeSeries;
  91. private boolean headPrimeDetail;
  92. private int headPrimeRowHPageBreak;
  93. //ГЛОБАЛЬНЫЙ ЗАГОЛОВОК перв.строка, строк в ОБРАЗЦЕ, имя колонки с номером по порядку,
  94. //признак начала страницы с детальной строки, в этой строке ставить разделитель страницы
  95. private int futPrimeRowB, futPrimeRowE, futPrimeRowHPageBreak;
  96. //ГЛОБАЛЬНЫЙ КОНЕЦ перв.строка, строк в ОБРАЗЦЕ, в этой строке ставить разделитель страницы
  97. private int detailRowB, detailRowE; //Номер перв., послед.строки ДЕТАЛЬНОЙ СТРОКИ
  98. private int headPageRowB, headPageRowE, headPageAfterRow;
  99. //Номер перв., строк, после какой строки ОБРАЗЦА печатать ВЕРХ СТРАНИЦЫ(3 Excel typ)
  100. private int topPageRowB, topPageRowE; //Номер перв., строк ВЕРХ СТРАНИЦЫ(13)
  101. private int bottomPageRowB, bottomPageRowE; //Номер перв., строк НИЗ СТРАНИЦЫ(4)
  102. /**
  103. * количество ИТОГОВ ПО КЛЮЧУ
  104. */
  105. private int keyTotCount;
  106. /**
  107. * тестируемая колонка ИТОГОВ ПО КЛЮЧУ
  108. */
  109. private Integer[] keyTotColTest = new Integer[dimensions];
  110. /**
  111. * первая строка шаблона ИТОГОВ ПО КЛЮЧУ
  112. */
  113. private Integer[] keyTotRowB = new Integer[dimensions];
  114. /**
  115. * количество строк шаблона ИТОГОВ ПО КЛЮЧУ
  116. */
  117. private Integer[] keyTotRowE = new Integer[dimensions];
  118. /**
  119. * первая детальная строка для ИТОГОВ ПО КЛЮЧУ
  120. */
  121. private Integer[] keyTotRowD = new Integer[dimensions];
  122. /**
  123. * признак группировки (появляются экселевские сворачивалки строк?) детальных строк ИТОГОВ ПО КЛЮЧУ
  124. */
  125. private Integer[] keyTotGroup = new Integer[dimensions];
  126. private String[][] keyTotColHide = new String[dimensions][dimensions2];
  127. private String[] keyTotModSerP1 = new String[dimensions], keyTotModSerP2 = new String[dimensions];
  128. private Boolean[] keyTotFlagHide = new Boolean[dimensions];
  129. // вот этот КАПЕЦ съехал !!!
  130. //Для ИТОГОВ ПО КЛЮЧУ номер тестируемой колонки
  131. //Перв.строка, строк в ОБРАЗЦЕ, перв.строка текущего интервала строк ДАННЫХ
  132. //Флаг скрыть повторяющееся значение, скрываемые колонки
  133. //Колонка(P1), при смене значений которой, в колонке(P2) формируется модифицированная серия
  134. //Признак группировки суммируемых строк (Group)
  135. private int keyPageCount; //Число ЗАГОЛОВОКИ ПО КЛЮЧУ
  136. private Integer[] keyPageColTest = new Integer[dimensions], keyPageRowB = new Integer[dimensions], keyPageRowE = new Integer[dimensions],
  137. keyPageRowD = new Integer[dimensions], keyPageGroup = new Integer[dimensions];
  138. private String[] keyPageSeries = new String[dimensions];
  139. //Для ЗАГОЛОВКИ ПО КЛЮЧУ номер тестируемой колонки
  140. //Перв.строка, строк в ОБРАЗЦЕ, признак новой страницы, имя колонки с номером по порядку
  141. //Признак группировки строк (Group)
  142. private boolean groupYes; //группировка есть в шаблоне
  143. private int formatCol, maxFormat; //колонка и максимальный уровень группировки
  144. private int pageFormat, totFormat;
  145. private int pageFormatCount; //Число ЗАГОЛОВОКИ для ФОРМАТИРОВАНИЯ
  146. private Integer[] pageFormatRowB = new Integer[dimensions], pageFormatRowE = new Integer[dimensions], pageFormatGroup = new Integer[dimensions];
  147. private Boolean[] pageFormatFormula = new Boolean[dimensions], pageFormatGroupHide = new Boolean[dimensions];
  148. private int totFormatCount; //Число ИТОГИ для ФОРМАТИРОВАНИЯ
  149. private Integer[] totFormatRowB = new Integer[dimensions], totFormatRowE = new Integer[dimensions], totFormatGroup = new Integer[dimensions];
  150. private Boolean[] totFormatFormula = new Boolean[dimensions], totFormatGroupHide = new Boolean[dimensions];
  151. private Boolean[] keyPageSecondRow = new Boolean[dimensions]; //признак ссылки строк типа 51-70 на вторую дет.строку
  152. private int addKeyTot; //ДОБАВКА К ИТОГАМ ПО КЛЮЧУ
  153. private String cellsAutoHeight; //Ячейки для автоподбора высоты AutoHeight(D4,D8)
  154. private int bottomPageColPgNmb, bottomPageRowPgNmb; //Ячейка для номера страницы
  155. private int topPageColPgNmb, topPageRowPgNmb, pgNmb; //Номер страницы
  156. //============================= Переменные для ДАННЫХ
  157. /**
  158. * Признак, что была хоть одна строка ДАННЫХ
  159. */
  160. private boolean flagB;
  161. /**
  162. * Первая строка ДАННЫХ
  163. */
  164. private int wRowB;
  165. /**
  166. * Последняя строка текущего интервала строк
  167. */
  168. private int wRowE;
  169. /**
  170. * Первая строка следующего интервала строк ДАННЫХ, она же текущая строка ДАННЫХ
  171. */
  172. private int wRow;
  173. /**
  174. * Перв.строка типа скопированного из ОБРАЗЦА в ДАННЫЕ (по идее нафиг здесь не нужна, используется локально каждый раз)
  175. */
  176. private int rangeRowB;
  177. private int i, j, k; //Глобально рабочие
  178. private String name_WorkSheet, text_KOP;
  179. private int indexPageUniq; //Имя активного листа
  180. private int rowWork;
  181. private int posSer;
  182. private String unC;
  183. private List<AreaReference> hideOneRow, hideFewRow;
  184. //+tolik
  185. public boolean uniOver;
  186. //-tolik
  187. private String shMainName;
  188. private String shAddName;
  189. private String dataBegName;
  190. public class CellValue /*implements Comparable<CellValue>*/ {
  191. private Object value;
  192. public CellValue(Object value){
  193. this.value = value;
  194. }
  195. /* not used
  196. public int compareTo(CellValue o){
  197. System.out.println("!!!CellValue.compareTo");
  198. if (o.value == null) return 1;
  199. else if (value != null) return value.toString().compareTo(((CellValue)o).value.toString());
  200. else return -1;
  201. }
  202. */
  203. @Override
  204. public boolean equals(Object obj) {
  205. if (obj instanceof CellValue){
  206. CellValue otherCellValue = (CellValue) obj;
  207. boolean thisValueEmpty = value == null || value.toString().trim().isEmpty();
  208. boolean otherValueEmpty = otherCellValue == null || otherCellValue.value == null || otherCellValue.value.toString().trim().isEmpty();
  209. if(thisValueEmpty && otherValueEmpty){
  210. return true;
  211. }
  212. else if (otherCellValue.value instanceof Double && value instanceof Double){
  213. return ((Double)value).equals((Double)otherCellValue.value);
  214. }else if (otherCellValue.value instanceof String && value instanceof String){
  215. return ((String)value).equals((String)otherCellValue.value);
  216. }
  217. else return false;
  218. }
  219. else return false;
  220. }
  221. public Object getValue() {
  222. return value;
  223. }
  224. }
  225. public JUniPrint(HSSFWorkbook wb){
  226. this.wb = wb;
  227. fontWhiteColor = wb.createFont();
  228. fontWhiteColor.setColor((short)1);
  229. String[] functionNames = new String[]{Nmb_Prop.class.getSimpleName(),
  230. Sum_Prop.class.getSimpleName(),
  231. FML.class.getSimpleName(),
  232. FMLR.class.getSimpleName()};
  233. FreeRefFunction[] functionImpls = new FreeRefFunction[]{Nmb_Prop.instance,
  234. Sum_Prop.instance,
  235. FML.instance,
  236. FMLR.instance};
  237. DefaultUDFFinder userUDFFinder = new DefaultUDFFinder(functionNames, functionImpls);
  238. evaluator = HSSFFormulaEvaluator.create(wb, null, userUDFFinder);
  239. this.dataBegName = RANGE_DATABEG;
  240. }
  241. public void init(String shMainName, String shAddName, String dataBegName) {
  242. this.shMainName = shMainName;
  243. this.shAddName = shAddName;
  244. this.dataBegName = dataBegName;
  245. if (this.shMainName != null && this.shAddName != null)
  246. sheets = new String[]{this.shMainName, this.shAddName};
  247. if (this.dataBegName == null) this.dataBegName = RANGE_DATABEG;
  248. useSpecialSheets = (shMainName != null);
  249. useGeneral = !useSpecialSheets;
  250. }
  251. private void calculate(HSSFSheet sh, byte mode){
  252. for(Iterator rit = sh.rowIterator(); rit.hasNext();) {
  253. HSSFRow r = (HSSFRow)rit.next();
  254. for(Iterator cit = r.cellIterator(); cit.hasNext();) {
  255. HSSFCell c = (HSSFCell)cit.next();
  256. if(c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
  257. try{
  258. switch (mode){
  259. case 0:
  260. evaluator.evaluate(c);
  261. break;
  262. case 1:
  263. evaluator.evaluateFormulaCell(c);
  264. break;
  265. case 2:
  266. evaluator.evaluateInCell(c);
  267. break;
  268. }
  269. }catch( Exception e){
  270. }
  271. }
  272. }
  273. }
  274. }
  275. private void uNIQ(Object a){
  276. }
  277. public void t_Query(String ws_Name, String query_Text, String ws_Dist){
  278. }
  279. private void setStyleRow(HSSFSheet ash, String strStyle, int row, int beCol, int countCol, int breakCol,
  280. Map<String, HSSFCellStyle[]> styleRowMap, HSSFFont font){
  281. int count =0;
  282. HSSFRow row1 = ash.getRow(row);
  283. HSSFCell cell;
  284. int endCol = beCol+countCol;
  285. if (!styleRowMap.containsKey(strStyle)){
  286. HSSFCellStyle[] rowStyle = new HSSFCellStyle[countCol];
  287. for(int indexCol = beCol; indexCol < endCol; indexCol++){
  288. cell = row1.getCell(indexCol);
  289. HSSFCellStyle style= wb.createCellStyle();
  290. style.cloneStyleFrom(cell.getCellStyle());
  291. style.setFont(font);
  292. if (indexCol != breakCol) cell.setCellStyle(style);
  293. rowStyle[count++] = style;
  294. }
  295. styleRowMap.put(strStyle, rowStyle);
  296. }else{
  297. for(int indexCol = beCol; indexCol < endCol; indexCol++){
  298. cell = row1.getCell(indexCol);
  299. if (cell != null && indexCol != breakCol)
  300. cell.setCellStyle(styleRowMap.get(strStyle)[count]);
  301. count++;
  302. }
  303. }
  304. }
  305. public void formatStyle(String[] sheets)throws JUniPrintException{
  306. if(namesMap != null) namesMap = ExcelUtils.createNamesMap(wb);
  307. HSSFName nameCUsing = useGeneral? ExcelUtils.getNamedRange(wb, RANGE_CUSING): ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_CUSING, sheets);
  308. HSSFName nameContentBegCol = useGeneral? ExcelUtils.getNamedRange(wb, RANGE_ContentBegCol): ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_ContentBegCol, sheets);
  309. HSSFName nameContentBegColRowHead = useGeneral? ExcelUtils.getNamedRange(wb, RANGE_ContentBegColRowHead): ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_ContentBegColRowHead, sheets);
  310. HSSFName nameDataBeg = useGeneral? ExcelUtils.getNamedRange(wb, dataBegName): ExcelUtils.getNamedRangeInSheets(namesMap, dataBegName, new String[]{name_WorkSheet});
  311. Map<String, HSSFCellStyle> styleMap = new HashMap<String, HSSFCellStyle>();
  312. Map<String, HSSFCellStyle[]> styleRowMap = new HashMap<String, HSSFCellStyle[]>();
  313. if(nameCUsing != null && nameContentBegCol != null && nameContentBegColRowHead != null && nameDataBeg != null){
  314. AreaReference ref = ExcelUtils.getReferanceNameRange(nameCUsing);
  315. String shName = ref.getFirstCell().getSheetName();
  316. int c = ref.getFirstCell().getCol();
  317. int r = ref.getFirstCell().getRow();
  318. HSSFCell cell = ExcelUtils.getCell(wb.getSheet(shName), r, c);
  319. int cusing = ((Double) cell.getNumericCellValue()).intValue()-1;
  320. ref= ExcelUtils.getReferanceNameRange(nameContentBegCol);
  321. shName = ref.getFirstCell().getSheetName();
  322. c = ref.getFirstCell().getCol();
  323. r = ref.getFirstCell().getRow();
  324. cell = ExcelUtils.getCell(wb.getSheet(shName), r, c);
  325. int colData = ((Double) cell.getNumericCellValue()).intValue()-1;
  326. ref = ExcelUtils.getReferanceNameRange(nameContentBegColRowHead);
  327. shName = ref.getFirstCell().getSheetName();
  328. c = ref.getFirstCell().getCol();
  329. r = ref.getFirstCell().getRow();
  330. cell = ExcelUtils.getCell(wb.getSheet(shName), r, c);
  331. int firstCol = ((Double) cell.getNumericCellValue()).intValue()-1;
  332. int countCol = cusing - firstCol;
  333. ref = ExcelUtils.getReferanceNameRange(nameDataBeg);
  334. HSSFSheet ash = wb.getSheet(ref.getFirstCell().getSheetName());
  335. int begRow = ref.getFirstCell().getRow();
  336. HSSFFont font1 = wb.createFont();
  337. font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  338. font1.setFontHeightInPoints((short)10);
  339. HSSFFont font2 = wb.createFont();
  340. font2.setItalic(true);
  341. HSSFFont font3 = wb.createFont();
  342. font3.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  343. HSSFFont font4 = wb.createFont();
  344. font4.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  345. font4.setItalic(true);
  346. font4.setFontHeightInPoints((short)8);
  347. for(int row = begRow; row <= ash.getLastRowNum(); row++){
  348. Object value = ExcelUtils.getCellValue(ExcelUtils.getCell(ash, row, 0));
  349. if(value == null) break;
  350. for(int col=0; col <= colData-firstCol; col++){
  351. value = ExcelUtils.getCellValue(ExcelUtils.getCell(ash, row, cusing+col));
  352. if (value != null){
  353. if (value instanceof String){
  354. String strValue = value.toString();
  355. cell = ExcelUtils.getCell(ash, row, firstCol + col);
  356. if( strValue.equals("total")){
  357. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font1);
  358. }else if(strValue.equals("h1")){
  359. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font1);
  360. }else if(strValue.equals("h2")){
  361. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font1);
  362. }else if(strValue.equals("det")){
  363. setStyleRow(ash, strValue, row, firstCol, countCol, cell.getColumnIndex(), styleRowMap, font1);
  364. if (!styleMap.containsKey(strValue)){
  365. HSSFCellStyle style= wb.createCellStyle();
  366. style.cloneStyleFrom(cell.getCellStyle());
  367. style.setIndention((short)1);
  368. style.setFont(font4);
  369. styleMap.put(strValue, style);
  370. }
  371. cell.setCellStyle(styleMap.get(strValue));
  372. }else if( strValue.equals("code") || strValue.equals("indexcol")){
  373. if (!styleMap.containsKey(strValue)){
  374. HSSFCellStyle style= wb.createCellStyle();
  375. style.cloneStyleFrom(cell.getCellStyle());
  376. style.setAlignment(style.ALIGN_CENTER);
  377. style.setFont(font3);
  378. styleMap.put(strValue, style);
  379. }
  380. cell.setCellStyle(styleMap.get(strValue));
  381. }else if(strValue.equals("d0")){
  382. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font3);
  383. }else if(strValue.equals("d1")){
  384. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font3);
  385. }else if(strValue.equals("d2")){
  386. if (!styleMap.containsKey(strValue)){
  387. HSSFCellStyle style= wb.createCellStyle();
  388. style.cloneStyleFrom(cell.getCellStyle());
  389. style.setIndention((short)1);
  390. styleMap.put(strValue, style);
  391. }
  392. cell.setCellStyle(styleMap.get(strValue));
  393. }else if(strValue.equals("d3")){
  394. if (!styleMap.containsKey(strValue)){
  395. HSSFCellStyle style= wb.createCellStyle();
  396. style.cloneStyleFrom(cell.getCellStyle());
  397. style.setIndention((short)2);
  398. styleMap.put(strValue, style);
  399. }
  400. cell.setCellStyle(styleMap.get(strValue));
  401. }else if(strValue.equals("d4")){
  402. if (!styleMap.containsKey(strValue)){
  403. HSSFCellStyle style= wb.createCellStyle();
  404. style.cloneStyleFrom(cell.getCellStyle());
  405. style.setIndention((short)3);
  406. styleMap.put(strValue, style);
  407. }
  408. cell.setCellStyle(styleMap.get(strValue));
  409. }else if(strValue.equals("d5")){
  410. setStyleRow(ash, strValue, row, firstCol, countCol, -1, styleRowMap, font2);
  411. }else if(strValue.equals("d6")){
  412. if (!styleMap.containsKey(strValue)){
  413. HSSFCellStyle style= wb.createCellStyle();
  414. style.cloneStyleFrom(cell.getCellStyle());
  415. style.setIndention((short)4);
  416. styleMap.put(strValue, style);
  417. }
  418. cell.setCellStyle(styleMap.get(strValue));
  419. }else if(strValue.equals("d7")){
  420. if (!styleMap.containsKey(strValue)){
  421. HSSFCellStyle style= wb.createCellStyle();
  422. style.cloneStyleFrom(cell.getCellStyle());
  423. style.setIndention((short)5);
  424. styleMap.put(strValue, style);
  425. }
  426. cell.setCellStyle(styleMap.get(strValue));
  427. }else if(strValue.equals("d8")){
  428. if (!styleMap.containsKey(strValue)){
  429. HSSFCellStyle style= wb.createCellStyle();
  430. style.cloneStyleFrom(cell.getCellStyle());
  431. style.setIndention((short)6);
  432. styleMap.put(strValue, style);
  433. }
  434. cell.setCellStyle(styleMap.get(strValue));
  435. }else if(strValue.equals("d9")){
  436. if (!styleMap.containsKey(strValue)){
  437. HSSFCellStyle style= wb.createCellStyle();
  438. style.cloneStyleFrom(cell.getCellStyle());
  439. style.setIndention((short)7);
  440. styleMap.put(strValue, style);
  441. }
  442. cell.setCellStyle(styleMap.get(strValue));
  443. }else if(strValue.equals("d10")){
  444. if (!styleMap.containsKey(strValue)){
  445. HSSFCellStyle style= wb.createCellStyle();
  446. style.cloneStyleFrom(cell.getCellStyle());
  447. style.setIndention((short)8);
  448. styleMap.put(strValue, style);
  449. }
  450. cell.setCellStyle(styleMap.get(strValue));
  451. }else if(!strValue.isEmpty()) {
  452. Short val = Short.parseShort(strValue);
  453. if(val > 0){
  454. setStyleRow(ash, strValue, row, firstCol, countCol, cell.getColumnIndex(), styleRowMap, font4);
  455. if (!styleMap.containsKey(strValue)){
  456. HSSFCellStyle style= wb.createCellStyle();
  457. style.cloneStyleFrom(cell.getCellStyle());
  458. style.setIndention((short)(4+val-1));
  459. style.setFont(font4);
  460. styleMap.put(strValue, style);
  461. }
  462. cell.setCellStyle(styleMap.get(strValue));
  463. }
  464. }
  465. }else if (value instanceof Double){
  466. Short val = (Short)value;
  467. if(val > 0){
  468. String strValue = val.toString();
  469. setStyleRow(ash, strValue, row, firstCol, countCol, cell.getColumnIndex(), styleRowMap, font1);
  470. if (!styleMap.containsKey(strValue)){
  471. HSSFCellStyle style= wb.createCellStyle();
  472. style.cloneStyleFrom(cell.getCellStyle());
  473. style.setIndention((short)(4+val-1));
  474. style.setFont(font4);
  475. styleMap.put(strValue, style);
  476. }
  477. cell.setCellStyle(styleMap.get(strValue));
  478. }
  479. }
  480. }
  481. }
  482. }
  483. }else
  484. throw new JUniPrintException("В шаблоне не задана одна из поименованных областей: '"+RANGE_CUSING+"', '"+
  485. RANGE_ContentBegCol+"', '"+RANGE_ContentBegColRowHead+"', '"+dataBegName+"'!");
  486. }
  487. public void uniPrint(boolean calc) throws JUniPrintException{
  488. int activeIndexSheet = wb.getActiveSheetIndex();
  489. HSSFSheet sheet = wb.getSheetAt(activeIndexSheet);
  490. uniPrint(sheet, calc);
  491. }
  492. public void uniPrint(int indexSheet, boolean calc) throws JUniPrintException{
  493. uniPrint(wb.getSheetAt(indexSheet), calc);
  494. }
  495. public void uniPrint(HSSFSheet sheet, boolean calc) throws JUniPrintException{
  496. //+tolik
  497. uniOver = false;
  498. //-tolik
  499. modelRowE = ExcelUtils.findMarkInColumn(sheet, "777", 0, 0);
  500. if (modelRowE < 0){
  501. throw new JUniPrintException("Нет строки с типом 777 - конец ОБРАЗЦА!");
  502. }
  503. nameDataBeg = null;
  504. nameDataRangeE = null;
  505. nameDataRangeB = null;
  506. nameDataPageE = null;
  507. model();//Заряжаем переменные для ОБРАЗЦА
  508. wRow = ExcelUtils.getReferanceNameRange(nameDataRangeB).getFirstCell().getRow();
  509. if(ExcelUtils.getCell(sheet, wRow, 0).getCellType() == HSSFCell.CELL_TYPE_BLANK){
  510. AreaReference areaReferance = new AreaReference("A"+(wRow+1)+":A"+(ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()));
  511. for(CellReference celRef:areaReferance.getAllReferencedCells()){
  512. ExcelUtils.setCellValue(ExcelUtils.getCell(sheet, celRef.getRow(), celRef.getCol()), 0);
  513. }
  514. }
  515. /*
  516. On Error Resume Next //Определяем есть ли группы
  517. ActiveSheet.Rows.OutlineLevel
  518. If Err.Number <> 0 Then On Error GoTo 0
  519. */
  520. rowWork = modelRowE + 1;
  521. if (headPageAfterRow == -1 && headPageRowB != -1) {headPage(sheet);} //Есть ВЕРХ СТРАНИЦЫ
  522. if (headPrimeRowB != -1) {
  523. headPrime(sheet); //Есть ГЛОБАЛЬНЫЙ ЗАГОЛОВОК
  524. }
  525. flagB = true;
  526. int count = 0;
  527. while(true){//Исходим из предположения - 999 послед.строка ДАННЫХ
  528. Object value = ExcelUtils.getCellValue(ExcelUtils.getCell(sheet, wRow, 0));
  529. if(value != null && value instanceof Double && (Double)value != 999){
  530. if ((Double)value == 0) { //Тип ДЕТАЛЬНОЙ СТРОКИ
  531. int detailRowIndex = wRow;
  532. if (flagB) {//Це начало
  533. formatLine(sheet);
  534. /*
  535. for (int i = 1; i <= lastCol; i++){
  536. HSSFCell cell = ExcelUtils.getCell(sheet, detailRowB, i);
  537. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  538. CellRangeAddress rangeRef = ExcelUtils.mergeArea(sheet, new CellReference(detailRowB, i));
  539. System.out.println("col"+i+"");
  540. int indexRow = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  541. ExcelUtils.paste(sheet, wRow, i, indexRow, i, ExcelUtils.copy(sheet, rangeRef), ExcelUtils.xlFormulas);
  542. }
  543. }
  544. */
  545. if (pageFormatCount != 0 || totFormatCount != 0) formatFormat(sheet);
  546. /*
  547. Rows(WRow & ":" & Range("DataRangeE").row - 1).Calculate
  548. If ((VarType(Rows(DetailRowB).WrapText) = vbNull) Or _
  549. (Rows(DetailRowB).WrapText = True)) And Len(CellsAutoHeight) = 0 Then
  550. Rows(WRow & ":" & Range("DataRangeE").row - 1).AutoFit
  551. End If
  552. */
  553. for(k = 0; k <= keyPageCount - 1; k++) {
  554. keyPage(sheet);
  555. }
  556. wRowB = wRow;
  557. for (int i = 0; i <= keyTotCount; i++) keyTotRowD[i] = wRow;
  558. flagB = false;
  559. if (keyTotCount == 0 && keyPageCount == 0) { //не нужен проход по детальным строкам
  560. wRowE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  561. wRow = wRowE + 1;
  562. break;
  563. }
  564. }else{
  565. //k =0;
  566. //System.out.println("wRow before = " + wRow);
  567. //int totRangeRowB = wRow;
  568. int keyTotIndex = checkKeyTot(sheet); //ИТОГИ ПО КЛЮЧУ
  569. //int keyRangeRowB = wRow;
  570. int keyPageRowsInserted = checkKeyPage(sheet); //ЗАГОЛОВКИ ПО КЛЮЧУ
  571. if (keyTotIndex >= 0) for (int i = 0; i <= keyTotIndex; i++) keyTotRowD[i] = keyTotRowD[i] + keyPageRowsInserted;
  572. //System.out.println("wRow after = " + wRow);
  573. if (hideDetailRows) ExcelUtils.getRow(sheet, detailRowIndex - 1).setZeroHeight(true);
  574. }
  575. wRowE = wRow;
  576. }
  577. wRow++;
  578. }else break;
  579. }
  580. if (flagB && (pageFormatCount != 0 || totFormatCount != 0)) formatFormat(sheet);
  581. int detailRowIndex = wRow;
  582. futPrime(sheet); //КОНЕЦ
  583. if (hideDetailRows) ExcelUtils.getRow(sheet, detailRowIndex - 1).setZeroHeight(true);
  584. if (topPageRowB >= 0 || bottomPageRowB >= 0) {
  585. if (!flagB) topPage(sheet);
  586. else modelDelete(sheet);
  587. }else modelDelete(sheet);
  588. if (!flagB && topPageRowB == -1 && bottomPageRowB == -1 && headPrimeDetail)
  589. hPCheck(); //двигаем разделители страниц
  590. ExcelUtils.deleteRow(sheet, ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow());
  591. wb.removeName(RANGE_DataRangeB);
  592. wb.removeName(RANGE_DataRangeE);
  593. wb.removeName(RANGE_DataPageE);
  594. // ActiveSheet.Calculate
  595. //+tolik
  596. uniOver = true;
  597. //-tolik
  598. // Application.Calculation = xlAutomatic
  599. // Application.CutCopyMode = False: Application.ScreenUpdating = True
  600. sheet.setColumnHidden(0, true);
  601. // Range("A1").Activate
  602. if(calc) calculate(sheet, (byte)2);
  603. }
  604. // ВЕРХ СТРАНИЦЫ тип 3
  605. private int headPage(HSSFSheet sh){
  606. rangeRowB = wRow;
  607. ExcelUtils.insertRows(sh, wRow, headPageRowE);
  608. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, headPageRowE);
  609. wRow += headPageRowE;
  610. ExcelUtils.paste(sh, "A"+(rangeRowB+1), ExcelUtils.copyRows(sh, headPageRowB, headPageRowB+headPageRowE-1));
  611. // sh.getPrintSetup().
  612. // wb.setPrintArea(wb.getSheetIndex(sh), "$" + rangeRowB+":$"+ (wRow - 1));
  613. wRowB = wRow;
  614. wRowE = wRow;
  615. bitch(sh);
  616. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowB+1), Integer.toString(wRowB+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  617. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowE+1), Integer.toString(wRowE+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  618. return headPageRowE;
  619. }
  620. private void bitch(HSSFSheet sh){
  621. }
  622. // ГЛОБАЛЬНЫЙ ЗАГОЛОВОК
  623. private void headPrime(HSSFSheet sh){
  624. rangeRowB = wRow;
  625. if (nameDataRangeE == null){
  626. Map<String, Map<String, HSSFName>> namesMap = ExcelUtils.createNamesMap(wb);
  627. nameDataRangeE = ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_DataRangeE, new String[]{name_WorkSheet});
  628. }
  629. if (!headPrimeSeries.isEmpty()){
  630. ExcelUtils.fill(sh, headPrimeSeries+(wRow+1), 1, ExcelUtils.xlValues);
  631. int indexCol = CellReference.convertColStringToIndex(headPrimeSeries);
  632. Calendar calendar = null;
  633. double numValue = 0;
  634. Object value = null;
  635. int step = 0;
  636. for(int row = wRow; row <= ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1; row++){
  637. if (row == wRow){
  638. value = ExcelUtils.getCellValue(ExcelUtils.getCell(sh, row, indexCol));
  639. if (value == null) break;
  640. if (value instanceof Date){
  641. calendar = Calendar.getInstance();
  642. calendar.setTime((Date)value);
  643. }else if(value instanceof Double){
  644. numValue = (Double) value;
  645. }
  646. }else{
  647. if (value instanceof Date){
  648. calendar.add(Calendar.DAY_OF_YEAR, step++);
  649. ExcelUtils.setCellValue(ExcelUtils.getCell(sh, row, indexCol), calendar.getTime());
  650. }else if(value instanceof Double){
  651. ExcelUtils.setCellValue(ExcelUtils.getCell(sh, row, indexCol), ++numValue);
  652. }
  653. }
  654. }
  655. }
  656. ExcelUtils.insertRows(sh, wRow, headPrimeRowE);
  657. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, headPrimeRowE);
  658. wRow += headPrimeRowE;
  659. ExcelUtils.paste(sh, rangeRowB, 0, ExcelUtils.copyRows(sh, headPrimeRowB, headPrimeRowB+headPrimeRowE-1));
  660. wRowB = wRow; wRowE = wRow;
  661. bitch(sh);
  662. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$" + (detailRowB+1), Integer.toString(wRowB+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  663. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$" + (detailRowE+1), Integer.toString(wRowE+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  664. //TODO ? условие или > или >=
  665. if (headPrimeRowHPageBreak >= 0){
  666. pBPrev(sh);
  667. sh.setRowBreak(rangeRowB + headPrimeRowHPageBreak - headPrimeRowB-1);
  668. }
  669. if (headPageAfterRow == headPrimeRowB && headPageRowB != -1) headPage(sh);
  670. }
  671. private void pBPrev(HSSFSheet sh){
  672. /*
  673. On Error Resume Next
  674. ActiveSheet.DisplayPageBreaks = True: ActiveWindow.View = xlPageBreakPreview
  675. If Err.Number <> 0 Then
  676. Application.ScreenUpdating = True: MsgBox ("Синсталлируйте принтер, Excel не может страницы расставить!"): End
  677. End If
  678. On Error GoTo 0
  679. */
  680. sh.setGridsPrinted(true);
  681. // wb.setPrintArea(wb.getSheetIndex(sh), 0, 4, 0, 30);
  682. }
  683. private void formatLine(HSSFSheet sh){
  684. int xxx, yyy , zzz;
  685. CellRangeAddressList workR;
  686. boolean flagVal;
  687. flagVal = false;
  688. workR = ExcelUtils.getSpecialCells(sh, new CellRangeAddress(detailRowB, detailRowB, 0, ExcelUtils.xlMaxNumCol-1), ExcelUtils.XlCellType.xlCellTypeAllValidation);
  689. if (workR != null) flagVal = true;
  690. ExcelBuffer buff = ExcelUtils.copyRows(sh, detailRowB, detailRowB);
  691. xxx = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  692. yyy = wRow; zzz = 4096;
  693. while( xxx >= yyy){
  694. ExcelUtils.pasteRows(sh, yyy, (xxx - yyy > zzz?yyy + zzz - 1:xxx), buff, ExcelUtils.xlFormulasAndNumberFormats);
  695. if (flagVal)
  696. ExcelUtils.pasteRows(sh, yyy, (xxx - yyy > zzz?yyy + zzz - 1:xxx), buff, ExcelUtils.xlValidation);
  697. yyy = (xxx - yyy > zzz?yyy + zzz:xxx+1);
  698. }
  699. }
  700. private void formatFormat(HSSFSheet sh) throws JUniPrintException{
  701. int xxx , begF, endF;
  702. xxx = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  703. for(int i = 0; i < pageFormatCount; i++)
  704. format1(sh, xxx, pageFormatRowB[i], pageFormatRowE[i], pageFormatFormula[i]);
  705. for(int i = 0; i < totFormatCount; i++)
  706. format1(sh, xxx, totFormatRowB[i], totFormatRowE[i], totFormatFormula[i]);
  707. if (pageFormat > 2 || totFormat > 2) sh.autoSizeColumn((short)formatCol, true);
  708. if (pageFormat > 2){
  709. // ActiveSheet.Outline.SummaryRow = xlAbove
  710. begF = wRowB - 1;
  711. endF = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  712. if(totFormatCount == 0) ExcelUtils.setCellValue(ExcelUtils.getCell(sh, endF, formatCol), 2);
  713. for(int i = 2; i < pageFormat; i++) format2(sh, begF, endF, i, pageFormat - 1);
  714. }else if (totFormat > 2){
  715. // ActiveSheet.Outline.SummaryRow = xlBelow
  716. begF = wRowB - 1;
  717. endF = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  718. if(pageFormatCount == 0) ExcelUtils.setCellValue(ExcelUtils.getCell(sh, begF, formatCol), 2);
  719. for(int i = 2; i < totFormat; i++) format2(sh, begF, endF, i, totFormat - 1);
  720. }
  721. if (pageFormat > 2 || totFormat > 2){
  722. ExcelUtils.clearColumn(sh, formatCol);
  723. sh.setColumnHidden(formatCol, true);
  724. }
  725. // If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False
  726. }
  727. private void format1(HSSFSheet sh, int xxx, int kFRowB, int kFRowE, boolean kFFormula) throws JUniPrintException{
  728. int yyy, zzz;
  729. CellRangeAddressList workR, sArea, workFormul;
  730. HSSFCell cell;
  731. boolean fl;
  732. if (kFFormula) {
  733. for(int row = kFRowB; row <= kFRowB+kFRowE; row++){
  734. for(int col = 1; col <= modelColE - 1; col++){
  735. cell = ExcelUtils.getCell(sh, row, col);
  736. if (cell.CELL_TYPE_FORMULA == HSSFCell.CELL_TYPE_FORMULA)
  737. ExcelUtils.setCellValue(cell, "");
  738. }
  739. }
  740. }
  741. yyy = wRowB; zzz = ExcelUtils.xlMaxNumRow-1;
  742. while (xxx >= yyy){
  743. ExcelUtils.autoFilter(sh, yyy - 1, 0, xxx, 0, null);
  744. ExcelUtils.autoFilter(sh, yyy - 1, 0, xxx, 0, ExcelUtils.getCellValue(ExcelUtils.getCell(sh, kFRowB, 0)));
  745. mods:{
  746. workR = ExcelUtils.getSpecialCells(sh, new CellRangeAddress(yyy, xxx - yyy > zzz?yyy + zzz - 1:xxx, 0, 0), ExcelUtils.XlCellType.xlCellTypeVisible);
  747. if (workR != null)
  748. if (yyy == xxx)
  749. if (ExcelUtils.getRow(sh, yyy).getZeroHeight()) break;
  750. else {
  751. workR = new CellRangeAddressList();
  752. workR.addCellRangeAddress(yyy, yyy, 0, 0);
  753. }
  754. if(zzz <= 1) break;
  755. if (workR != null && workR.countRanges() > 0){
  756. if(kFRowE > 1){
  757. CellRangeAddress cellReff = workR.getCellRangeAddress(0);
  758. if(cellReff.getLastRow()-cellReff.getFirstRow()+1 != kFRowE){
  759. ExcelUtils.autoFilter(sh, yyy - 1, 0, xxx, 0, null);
  760. throw new JUniPrintException("Несовпадение числа строк типа "+
  761. ExcelUtils.getCellValue(ExcelUtils.getCell(sh, kFRowB, 1))+" в шаблоне и данных!");
  762. }
  763. cellReff = workR.getCellRangeAddress(workR.countRanges()-1);
  764. if(cellReff.getLastRow()-cellReff.getFirstRow()+1 != kFRowE){
  765. zzz++;
  766. break mods;
  767. }
  768. }
  769. ExcelUtils.autoFilter(sh, yyy - 1, 0, xxx, 0, null);
  770. ExcelBuffer buff = ExcelUtils.copyRows(sh, kFRowB, kFRowB+kFRowE-1);
  771. // workR.EntireRow.PasteSpecial Paste:=xlFormats
  772. CellRangeAddressList areas = ExcelUtils.getEntireRow(workR);
  773. for(int iArea=0; iArea < areas.countRanges(); iArea++)
  774. ExcelUtils.paste(sh, areas.getCellRangeAddress(iArea), buff, ExcelUtils.xlFormats);
  775. if (kFFormula){
  776. workFormul = ExcelUtils.getSpecialCells(sh, new CellRangeAddress(kFRowB, kFRowB+kFRowE-1, 1, modelColE - 1),
  777. ExcelUtils.XlCellType.xlCellTypeFormulas);
  778. sArea = ExcelUtils.getEntireColumn(workFormul);
  779. if (sArea != null)
  780. for(int indexArea=0; indexArea <sArea.countRanges(); indexArea++){
  781. CellRangeAddress crA = ExcelUtils.intersectRectangular(sArea.getCellRangeAddress(indexArea),
  782. new CellRangeAddress(kFRowB, kFRowB+kFRowE-1, 0, ExcelUtils.xlMaxNumCol-1));
  783. if (crA != null){
  784. buff = ExcelUtils.copy(sh, crA);
  785. crA = ExcelUtils.intersectRectangular(sArea.getCellRangeAddress(indexArea),
  786. areas.getCellRangeAddress(0));
  787. if (crA != null) ExcelUtils.paste(sh, crA, buff, ExcelUtils.xlFormulas);
  788. }else{
  789. //!!!!
  790. }
  791. }
  792. }
  793. if (pageFormat > 2 || totFormat > 2) {
  794. for(int iArea=0; iArea < areas.countRanges(); iArea++){
  795. CellRangeAddress crA = ExcelUtils.intersectRectangular(new CellRangeAddress(0, ExcelUtils.xlMaxNumRow-1, formatCol, formatCol),
  796. areas.getCellRangeAddress(iArea));
  797. ExcelUtils.fill(sh, new CellRangeAddress(kFRowB, kFRowB+kFRowE-1, formatCol, formatCol), crA, ExcelUtils.xlValues);
  798. }
  799. }
  800. if (lastCol >= formatCol){
  801. if (ExcelUtils.hasFormula(sh, kFRowB, formatCol, kFRowB+kFRowE-1, lastCol - formatCol + 1) == null){
  802. buff = ExcelUtils.copy(sh, kFRowB, formatCol, kFRowB+kFRowE-1, lastCol - formatCol);
  803. for(int iArea=0; iArea < areas.countRanges(); iArea++){
  804. CellRangeAddress crA = ExcelUtils.intersectRectangular(
  805. new CellRangeAddress(0,
  806. ExcelUtils.xlMaxNumRow-1,
  807. formatCol,
  808. lastCol - formatCol),
  809. areas.getCellRangeAddress(iArea));
  810. ExcelUtils.paste(sh, crA, buff, ExcelUtils.xlFormulas);
  811. }
  812. }
  813. }
  814. }
  815. yyy = xxx - yyy > zzz ? yyy + zzz: xxx+ 1;
  816. }
  817. }
  818. ExcelUtils.autoFilter(sh, yyy - 1, 0, xxx, 0, null);
  819. // If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False
  820. }
  821. private void format2(HSSFSheet sh, int begF, int endF, int numOutl, int maxOutl){
  822. int begRow =0, xxx, yyy, zzz;
  823. CellRangeAddressList workR, sArea;
  824. boolean flagBegin;
  825. ExcelUtils.autoFilter(sh, begF, formatCol, endF, formatCol, null);
  826. ExcelUtils.autoFilter(sh, begF, formatCol, endF, formatCol, new Double(numOutl));
  827. xxx = endF; yyy = begF; zzz = ExcelUtils.xlMaxNumRow-1; flagBegin = true;
  828. while(xxx > yyy){
  829. mods:
  830. {
  831. workR = ExcelUtils.getSpecialCells(sh, new CellRangeAddress(yyy, xxx - yyy > zzz?yyy + zzz - 1:xxx, formatCol, formatCol), ExcelUtils.XlCellType.xlCellTypeVisible);
  832. if (yyy == xxx){
  833. if (ExcelUtils.getRow(sh, yyy).getZeroHeight()) break;
  834. else {
  835. workR = new CellRangeAddressList();
  836. workR.addCellRangeAddress(yyy, yyy, 0, 0);
  837. }
  838. }
  839. if(zzz <= 1) break;
  840. if (workR != null){
  841. CellRangeAddress cRA = workR.getCellRangeAddress(workR.countRanges()-1);
  842. Object value = ExcelUtils.getCellValue(
  843. ExcelUtils.getCell(sh, cRA.getLastRow()+ 1, formatCol));
  844. if(value != null && value instanceof Double && value.equals(new Double(numOutl))){
  845. zzz++;
  846. break mods;
  847. }
  848. for(int i=0; i< workR.countRanges(); i++){
  849. if(flagBegin){
  850. begRow = workR.getCellRangeAddress(i).getLastRow()+1;
  851. flagBegin = false;
  852. }else{
  853. // Rows(BegRow & ":" & sArea.row - 1).OutlineLevel = NumOutl
  854. sh.groupRow(begRow, workR.getCellRangeAddress(i).getFirstRow()-1);
  855. begRow = workR.getCellRangeAddress(i).getLastRow()+1;
  856. }
  857. }
  858. if (maxOutl != numOutl) {
  859. for(int i=0; i< workR.countRanges(); i++){
  860. cRA = ExcelUtils.intersectRectangular(workR.getCellRangeAddress(i),
  861. new CellRangeAddress(0, ExcelUtils.xlMaxNumRow-1, formatCol, formatCol));
  862. ExcelUtils.fill(sh, cRA, numOutl + 1, ExcelUtils.xlValues);
  863. }
  864. }
  865. }
  866. yyy = xxx - yyy > zzz ? yyy + zzz : xxx + 1;
  867. }
  868. }
  869. ExcelUtils.autoFilter(sh, begF, formatCol, endF, formatCol, null);
  870. // If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False
  871. }
  872. private int keyPage(HSSFSheet sh){
  873. int insertedRows = 0;
  874. if(nameDataRangeE == null){
  875. Map<String, Map<String, HSSFName>> namesMap = ExcelUtils.createNamesMap(wb);
  876. nameDataRangeE = ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_DataRangeE, new String[]{name_WorkSheet});
  877. }
  878. rangeRowB = wRow;
  879. ExcelUtils.insertRows(sh, wRow, keyPageRowE[k]);
  880. insertedRows = insertedRows + keyPageRowE[k];
  881. wRow += keyPageRowE[k];
  882. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, wRow + keyPageRowE[k]);
  883. ExcelBuffer buff = ExcelUtils.copyRows(sh, keyPageRowB[k], keyPageRowB[k]+keyPageRowE[k]-1);
  884. ExcelUtils.paste(sh, rangeRowB, 0, buff);
  885. bitch(sh);
  886. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowB+1), Integer.toString(wRow+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  887. if (flagB && headPageAfterRow == keyPageRowB[k] && headPageRowB != -1)
  888. insertedRows = insertedRows + headPage(sh); //Есть ВЕРХ СТРАНИЦЫ тип 3
  889. if (!keyPageSeries[k].isEmpty()){
  890. int rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow()-1;
  891. ExcelUtils.fill(sh, keyPageSeries[k]+""+(wRow+1), 1, ExcelUtils.xlValues);
  892. AreaReference areaRef = new AreaReference(keyPageSeries[k] +""+(wRow+1) + ":" + keyPageSeries[k]+""+(rowNameDataRangeE+1));
  893. if(!areaRef.isSingleCell()){
  894. for(int col = areaRef.getFirstCell().getCol(); col <= areaRef.getLastCell().getCol(); col++){
  895. Double numValue = 0d;
  896. for(int row = areaRef.getFirstCell().getRow(); row <= areaRef.getLastCell().getRow(); row++){
  897. if (row == areaRef.getFirstCell().getRow()){
  898. HSSFRow row0 = sh.getRow(row);
  899. if (row0 != null){
  900. HSSFCell cell = row0.getCell(col);
  901. if (cell != null){
  902. Object value = ExcelUtils.getCellValue(cell);
  903. if (value != null && value instanceof Number){
  904. numValue = ((Number)value).doubleValue();
  905. numValue +=1;
  906. }else break;
  907. }else break;
  908. }
  909. else break;
  910. }else{
  911. ExcelUtils.setCellValue(ExcelUtils.getCell(sh, row, col), numValue);
  912. numValue +=1;
  913. }
  914. }
  915. }
  916. }
  917. }
  918. return insertedRows;
  919. }
  920. /**
  921. * Проверяет не изменилось ли значение в одной из колонок содержащих ключи для итогов.
  922. * Если изменение найдено, вставляет строки итогов в соответствии с шаблоном и
  923. * возвращает индекс элемента keyTotGroup (в т.ч. keyTotRowD и т.п.), по которому было найдено изменение.
  924. * Если изменения нет, возвращает -1.
  925. *
  926. * @param sh - worksheet
  927. * @return индекс элемента keyTotGroup (в т.ч. keyTotRowD и т.п.)
  928. */
  929. private int checkKeyTot(HSSFSheet sh){
  930. int keyTotIndex = -1;
  931. boolean flagType6;
  932. int countWorkRow, rangeRowHid =0;
  933. int numModSer;
  934. Object modSerVal;
  935. for (int j = keyTotCount - 1; j >= 0; j--){
  936. CellValue value1 = new CellValue(ExcelUtils.getCellValue(ExcelUtils.getCell(sh, wRowE, keyTotColTest[j])));
  937. CellValue value2 = new CellValue(ExcelUtils.getCellValue(ExcelUtils.getCell(sh, wRow, keyTotColTest[j])));
  938. if (!value1.equals(value2)){
  939. //System.out.println("checkKeyTot... values differs");
  940. flagType6 = true;
  941. for (int k = 0; k <= j; k++){
  942. if (keyTotGroup[k] > 0){
  943. // ActiveSheet.Outline.SummaryRow = xlBelow
  944. sh.groupRow(keyTotRowD[k], wRow - 1);
  945. }
  946. countWorkRow = 0;
  947. if (addKeyTot != 0) { //есть строка типа 6
  948. for(int iRow=keyTotRowD[k]; iRow <=wRow - 1; iRow++){
  949. Object obj =
  950. ExcelUtils.getCellValue(ExcelUtils.getCell(sh, iRow, 0));
  951. if (obj != null && obj instanceof Double && obj.equals(0d))
  952. countWorkRow++;
  953. }
  954. if (countWorkRow == 1 && flagType6){
  955. flagType6 = false;
  956. ExcelUtils.insertRows(sh, wRow, 1);
  957. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, 1);
  958. ExcelBuffer buff = ExcelUtils.copyRows(sh, addKeyTot, addKeyTot);
  959. ExcelUtils.pasteRows(sh, wRow, wRow, buff, ExcelUtils.xlAll);
  960. wRow = wRow + 1;
  961. rangeRowHid = wRow;
  962. }
  963. }
  964. rangeRowB = wRow; //печать ИТОГИ ПО КЛЮЧУ
  965. HSSFCell cell = null;
  966. ExcelUtils.insertRows(sh, wRow, keyTotRowE[k]); //!!! долго работатет метод shiftRows !!!!!
  967. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, keyTotRowE[k]);
  968. wRow += keyTotRowE[k];
  969. ExcelBuffer buff = ExcelUtils.copyRows(sh, keyTotRowB[k], keyTotRowB[k]+keyTotRowE[k]-1);
  970. ExcelUtils.pasteRows(sh, rangeRowB, rangeRowB+keyTotRowE[k]-1, buff, ExcelUtils.xlAll);
  971. bitch(sh);
  972. //System.out.println("replace " + "$"+(detailRowB+1) + " to " + (keyTotRowD[k]+1));
  973. ExcelUtils.replaceRows(sh, rangeRowB, wRow, "$"+(detailRowB+1), new Integer(keyTotRowD[k]+1).toString(), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  974. //System.out.println("replace " + "$"+(detailRowE+1) + " to " + (wRowE+1));
  975. ExcelUtils.replaceRows(sh, rangeRowB, wRow, "$"+(detailRowE+1), Integer.toString(wRowE+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  976. //System.out.println("replace " + "$"+(detailRowB) + " to " + (keyTotRowD[k]));
  977. ExcelUtils.replaceRows(sh, rangeRowB, wRow, "$"+(detailRowB), Integer.toString(keyTotRowD[k]), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  978. if (countWorkRow == 1)
  979. for(int iRow=rangeRowHid; iRow <= wRow - 1; iRow++)
  980. ExcelUtils.getRow(sh, iRow).setZeroHeight(true);
  981. if (keyTotModSerP1[k] != null && !keyTotModSerP1[k].isEmpty()){ //Есть модифицированная серия
  982. numModSer = 0;
  983. modSerVal = null;
  984. for (int workI = keyTotRowD[k]; workI <= wRowE; workI++){
  985. Object cellValue = ExcelUtils.getCellValue(ExcelUtils.getCell(sh, workI, 0));
  986. if (cellValue != null && cellValue instanceof Double && cellValue.equals(0d)){
  987. Object cellValue2 = ExcelUtils.getCellValue(
  988. ExcelUtils.getCell(sh, workI, CellReference.convertColStringToIndex(keyTotModSerP1[k])));
  989. if (numModSer == 0 || cellValue2 != null && !cellValue2.equals(modSerVal)){
  990. numModSer = numModSer + 1;
  991. ExcelUtils.setCellValue(ExcelUtils.getCell(sh, workI, CellReference.convertColStringToIndex(keyTotModSerP2[k])), numModSer);
  992. modSerVal = cellValue2;
  993. }else{
  994. cell = ExcelUtils.getCell(sh, workI, CellReference.convertColStringToIndex(keyTotModSerP2[k]));
  995. ExcelUtils.setCellValue(cell, numModSer);
  996. cell.setCellStyle(arrCellStyleTextWhiteColor[cell.getColumnIndex()]);
  997. }
  998. }
  999. }
  1000. }
  1001. }
  1002. keyTotIndex = j;
  1003. for (int k = 0; k

Large files files are truncated, but you can click here to view the full file