PageRenderTime 228ms CodeModel.GetById 21ms 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
  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 <= keyTotIndex; k++) keyTotRowD[k] = wRow;
  1004. break;
  1005. }
  1006. if (value1.equals(value2) && keyTotFlagHide[j]){ //Значение ключа не изменилось - мочи его!!!
  1007. int k = 0;
  1008. while(!keyTotColHide[j][k].isEmpty()){
  1009. HSSFCell cell = ExcelUtils.getCell(sh, wRow, CellReference.convertColStringToIndex(keyTotColHide[j][k]));
  1010. cell.setCellStyle(arrCellStyleTextWhiteColor[cell.getColumnIndex()]);
  1011. k++;
  1012. }
  1013. }
  1014. }
  1015. return keyTotIndex;
  1016. }
  1017. /**
  1018. * Проверяет не изменилось ли значение в одной из колонок содержащих ключи для заголовков.
  1019. * Если изменение найдено, вставляет строки заголовков в соответствии с шаблоном и
  1020. * возвращает количество вставленных строк.
  1021. * Если изменения нет, возвращает 0.
  1022. *
  1023. * @param sh - worksheet
  1024. * @return количество вставленных строк
  1025. */
  1026. private int checkKeyPage(HSSFSheet sh){
  1027. int insertedRows = 0;
  1028. boolean flagNewPage = false;
  1029. for (int j = 0; j<=keyPageCount - 1; j++){
  1030. CellValue value1 = new CellValue(ExcelUtils.getCellValue(ExcelUtils.getCell(sh, wRowE, keyPageColTest[j])));
  1031. CellValue value2 = new CellValue(ExcelUtils.getCellValue(ExcelUtils.getCell(sh, wRow, keyPageColTest[j])));
  1032. if(!value1.equals(value2)){
  1033. //System.out.println("checkKeyPage #" + j + "... values differs ([" + value1.value + "], [" + value2.value + "])");
  1034. rowWork = wRow;
  1035. for (k = j; k<= keyPageCount - 1; k++){
  1036. //System.out.println("keyPage from checkKeyPage #" + k);
  1037. insertedRows = insertedRows + keyPage(sh); //печать
  1038. if (keyPageRowD[k] > 0) flagNewPage = true;
  1039. }
  1040. break;
  1041. }
  1042. }
  1043. if(!flagB && flagNewPage){
  1044. pBPrev(sh);
  1045. sh.setRowBreak(rowWork-1);
  1046. // ActiveWindow.View = xlNormalView
  1047. }
  1048. return insertedRows;
  1049. }
  1050. private void futPrime(HSSFSheet sh){
  1051. int workFutPrimeRowHPageBreak = -1, ll ;
  1052. if (!flagB) checkKeyTot(sh);// 'Запомним строку, чтобы вставить НИЗ СТРАНИЦЫ
  1053. nameDataPageE = ExcelUtils.createNameRange(RANGE_DataPageE, "'"+name_WorkSheet+"'!$A$"+(wRow - 1), wb);
  1054. namesMap = ExcelUtils.createNamesMap(wb);
  1055. if (futPrimeRowB >= 0){ //Есть ГЛОБАЛЬНЫЙ КОНЕЦ
  1056. bitch(sh);
  1057. rangeRowB = wRow;
  1058. if (indexPageUniq == 0) { //'Нет Uniq(X:X)
  1059. ExcelUtils.insertRows(sh, wRow, futPrimeRowE);
  1060. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, futPrimeRowE);
  1061. wRow += futPrimeRowE;
  1062. ExcelBuffer buff = ExcelUtils.copyRows(sh, futPrimeRowB, futPrimeRowB+futPrimeRowE-1);
  1063. ExcelUtils.pasteRows(sh, rangeRowB, rangeRowB+futPrimeRowE-1, buff, ExcelUtils.xlAll);
  1064. if (futPrimeRowHPageBreak >= 0){
  1065. workFutPrimeRowHPageBreak = rangeRowB + futPrimeRowHPageBreak - futPrimeRowB;
  1066. }
  1067. if (flagB) { wRowB = wRow; wRowE = wRow;}//нет детальных строк
  1068. }else{//Есть Uniq(X:X)
  1069. for (int i = futPrimeRowB; i<= futPrimeRowB + futPrimeRowE - 1; i++){
  1070. if (futPrimeRowHPageBreak >= 0 && futPrimeRowHPageBreak == i)
  1071. workFutPrimeRowHPageBreak = wRow;
  1072. int posSer = -1;
  1073. for (int j = 1; j<= modelColE; j++){// 'Поиск Uniq(X:X)
  1074. HSSFCell cell = ExcelUtils.getCell(sh, i, j);
  1075. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  1076. String formula = cell.getCellFormula();
  1077. if (formula != null){
  1078. posSer = formula.indexOf("uniq(");
  1079. if (posSer >= 0){
  1080. unC = formula.substring(posSer + 5, posSer+8); //определить колонку
  1081. unC = unC.substring(0, unC.indexOf(":", 1));
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. if (posSer >= 0){
  1088. HSSFSheet uniqShete = wb.getSheetAt(indexPageUniq);
  1089. int indexCol = CellReference.convertColStringToIndex(unC);
  1090. ll = (int)((Double)ExcelUtils.getCellValue(ExcelUtils.getCell(uniqShete, 0, indexCol))-2);
  1091. ExcelUtils.insertRows(sh, wRow, ll);
  1092. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, ll);
  1093. ExcelBuffer buff = ExcelUtils.copyRows(sh, i, i);
  1094. ExcelUtils.pasteRows(sh, wRow, wRow+ll-1, buff, ExcelUtils.xlAll);
  1095. for (int j = 2; j<= ll + 1; j++){
  1096. Object value = ExcelUtils.getCellValue(ExcelUtils.getCell(uniqShete, 1, indexCol));
  1097. Object value2 = ExcelUtils.getCellValue(ExcelUtils.getCell(uniqShete, j, indexCol));
  1098. if (value2 != null)
  1099. ExcelUtils.replaceRows(sh, wRow, wRow, value, value2, ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1100. else
  1101. ExcelUtils.replaceRows(sh, wRow, wRow, value, "0", ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1102. wRow++;
  1103. }
  1104. }else{
  1105. ExcelUtils.insertRows(sh, wRow, 1);
  1106. ExcelUtils.upadteReferenceNameAfterInsertRows(namesMap, new String[]{name_WorkSheet}, wRow, 1);
  1107. ExcelBuffer buff = ExcelUtils.copyRows(sh, i, i);
  1108. ExcelUtils.pasteRows(sh, wRow, wRow, buff, ExcelUtils.xlAll);
  1109. wRow++;
  1110. }
  1111. }
  1112. if(flagB) {wRowB = wRow; wRowE = wRow; }//нет детальных строк}
  1113. //Application.DisplayAlerts = False
  1114. wb.removeSheetAt(indexPageUniq);
  1115. //Application.DisplayAlerts = True
  1116. //Worksheets(Name_WorkSheet).Activate
  1117. }
  1118. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowB+1), Integer.toString(wRowB+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1119. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowE+1), Integer.toString(wRowE+1), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1120. ExcelUtils.replaceRows(sh, rangeRowB, wRow - 1, "$"+(detailRowB), Integer.toString(wRowB), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1121. if (futPrimeRowHPageBreak >= 0){
  1122. pBPrev(sh);
  1123. sh.setRowBreak(workFutPrimeRowHPageBreak-1);
  1124. // ActiveWindow.View = xlNormalView
  1125. }
  1126. }
  1127. }
  1128. private void modelDelete(HSSFSheet sh){
  1129. int lastRow0, replaceRow;
  1130. HSSFShape shape;
  1131. boolean dZeros;
  1132. double findValue;
  1133. /*
  1134. For Each Sh In ActiveSheet.Shapes
  1135. On Error Resume Next
  1136. If Sh.TopLeftCell.row <= ModelRowE And Sh.BottomRightCell.row <= ModelRowE _
  1137. Then Sh.Visible = False
  1138. On Error GoTo 0
  1139. Next
  1140. */
  1141. // DZeros = ActiveWindow.DisplayZeros
  1142. // if (nameDataRangeE == null){
  1143. // Map<String, Map<String, HSSFName>> namesMap = ExcelUtils.createNamesMap(wb);
  1144. // nameDataRangeE = ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_DataRangeE, new String[]{name_WorkSheet});
  1145. // }
  1146. for (int i = 0; i <= keyPageCount - 1; i++){
  1147. if (keyPageSecondRow[i] || keyPageGroup[i] > 0) {
  1148. //If Not DZeros Then ActiveWindow.DisplayZeros = True
  1149. findValue = 0;
  1150. for (int j = 0; j<= keyTotCount - 1; j++)
  1151. if (keyPageColTest[i].equals(keyTotColTest[j])){
  1152. findValue = ((Double)ExcelUtils.getCellValue(ExcelUtils.getCell(sh, keyTotRowB[j], 0))).intValue();
  1153. break;
  1154. }
  1155. int rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1156. HSSFCell findCell = ExcelUtils.find(sh, 0, 0, rowNameDataRangeE, 0, findValue, ExcelUtils.xlValues,
  1157. ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlPrevious);
  1158. if (findCell != null){
  1159. lastRow0 = findCell.getRowIndex();
  1160. replaceRow = findCell.getRowIndex();
  1161. if (findValue != 0) replaceRow -= keyTotRowE[j];
  1162. while(true){
  1163. Object searchValue = ExcelUtils.getCellValue(ExcelUtils.getCell(sh, keyPageRowB[i], 0));
  1164. findCell = ExcelUtils.find(sh, 0, 0, findCell.getRowIndex(), 0, searchValue, ExcelUtils.xlValues,
  1165. ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlPrevious);
  1166. if(keyPageSecondRow[i]){
  1167. bitch(sh);
  1168. if (findCell != null)
  1169. ExcelUtils.replaceRows(sh, findCell.getRowIndex()-keyPageRowE[i]+1, findCell.getRowIndex(),
  1170. "$"+(detailRowE+1), Integer.toString(replaceRow+1), ExcelUtils.xlFormulas,
  1171. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1172. }
  1173. if (keyPageGroup[i] > 0){
  1174. //ActiveSheet.Outline.SummaryRow = xlAbove
  1175. if (findCell != null)
  1176. sh.groupRow(findCell.getRowIndex()+1, replaceRow);
  1177. }
  1178. if (findCell != null)
  1179. findCell = ExcelUtils.find(sh, 0, 0, findCell.getRowIndex(), 0, findValue,
  1180. ExcelUtils.xlValues, ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlPrevious);
  1181. if (findCell != null) replaceRow = findCell.getRowIndex();
  1182. if (findCell == null || lastRow0 == replaceRow) break;
  1183. if (findValue != 0) replaceRow -= keyTotRowE[j];
  1184. }
  1185. }
  1186. }
  1187. }
  1188. //ActiveWindow.DisplayZeros = DZeros
  1189. bitch(sh);
  1190. dZeros = true;
  1191. int rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1192. if (rowNameDataRangeE >= 100){
  1193. ExcelUtils.replaceRows(sh, 0, modelRowE,
  1194. "$"+(detailRowB+1), Integer.toString(detailRowB+1), ExcelUtils.xlFormulas,
  1195. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1196. ExcelUtils.replaceRows(sh, 0, modelRowE,
  1197. "$"+(detailRowE+1), Integer.toString(detailRowE+1), ExcelUtils.xlFormulas,
  1198. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1199. ExcelUtils.replaceRows(sh, 0, modelRowE,
  1200. "$"+(detailRowB), Integer.toString(detailRowB), ExcelUtils.xlFormulas,
  1201. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1202. HSSFCell findCell = ExcelUtils.find(sh, 0, 0, modelRowE, ExcelUtils.xlMaxNumRow, "$1", ExcelUtils.xlFormulas,
  1203. ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlNext);
  1204. if (findCell== null) dZeros = false;
  1205. }
  1206. if (dZeros){
  1207. ExcelUtils.replaceRows(sh, 0, rowNameDataRangeE-1,
  1208. "$"+1, Integer.toString(1), ExcelUtils.xlFormulas,
  1209. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1210. ExcelUtils.replaceRows(sh, 0, rowNameDataRangeE-1,
  1211. "$"+2, Integer.toString(rowNameDataRangeE), ExcelUtils.xlFormulas,
  1212. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1213. }
  1214. //удаления ОБРАЗЦА
  1215. //очистка хвостовичка
  1216. //ExcelUtils.deleteRow(sh, rowNameDataRangeE);
  1217. // sh.getRow(rowNameDataRangeE).setZeroHeight(true);
  1218. for(int iRow=0; iRow <= modelRowE; iRow++){
  1219. HSSFRow delRow = sh.getRow(iRow);
  1220. if (delRow != null){
  1221. delRow.setZeroHeight(true);
  1222. Iterator it = delRow.cellIterator();
  1223. while(it.hasNext())
  1224. delRow.removeCell((HSSFCell)it.next());
  1225. }
  1226. }
  1227. // sh.shiftRows(modelRowE+1, sh.getLastRowNum(), -(modelRowE+1));
  1228. if(cellsAutoHeight != null && !cellsAutoHeight.isEmpty()){
  1229. calculate(sh, (byte)1);
  1230. // ActiveSheet.Calculate
  1231. if (hideOneRow != null){
  1232. int i = 1024;
  1233. rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1234. int j = sh.getFirstRowNum();
  1235. while(rowNameDataRangeE -1 >=j){
  1236. CellRangeAddress crB = new CellRangeAddress(j, i, 0, ExcelUtils.xlMaxNumCol-1);
  1237. for(AreaReference area:hideOneRow){
  1238. CellRangeAddress res = ExcelUtils.intersectRectangular(new CellRangeAddress(
  1239. area.getFirstCell().getRow(), area.getLastCell().getRow(),
  1240. area.getFirstCell().getCol(), area.getLastCell().getCol()), crB);
  1241. if (res != null){
  1242. CellRangeAddressList list = ExcelUtils.getSpecialCells(sh, res, ExcelUtils.XlCellType.xlCellTypeFormulas);
  1243. if (list != null){
  1244. CellRangeAddressList l = ExcelUtils.getEntireRow(list);
  1245. if (l != null){
  1246. for(int ii=0; ii<l.countRanges(); ii++){
  1247. CellRangeAddress workRange = l.getCellRangeAddress(ii);
  1248. for(int row = workRange.getFirstRow(); row <= workRange.getLastRow(); row++)
  1249. ExcelUtils.getRow(sh, row).setZeroHeight(false);
  1250. CellRangeAddressList rHeight = ExcelUtils.getSpecialCells(sh, workRange , ExcelUtils.XlCellType.xlCellTypeVisible);
  1251. if (rHeight != null){
  1252. rHeight = ExcelUtils.getEntireRow(rHeight);
  1253. ExcelUtils.hiddenRows(sh, rHeight, false);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. }
  1260. j = i + 1;
  1261. i = i + 1024;
  1262. }
  1263. }
  1264. if (hideFewRow != null){
  1265. boolean wRHidden = false;
  1266. for(AreaReference area:hideFewRow){
  1267. CellRangeAddress cra = new CellRangeAddress(
  1268. area.getFirstCell().getRow(), area.getLastCell().getRow(),
  1269. area.getFirstCell().getCol(), area.getLastCell().getCol());
  1270. CellRangeAddressList list = ExcelUtils.getSpecialCells(sh, cra, ExcelUtils.XlCellType.xlCellTypeFormulas);
  1271. if (list != null && list.getSize() >0){
  1272. for(int jj=0; jj < list.countRanges(); jj++){
  1273. CellRangeAddress crb = list.getCellRangeAddress(jj);
  1274. wRHidden = ExcelUtils.getRow(sh, crb.getFirstRow()).getZeroHeight();
  1275. HSSFCell cell = ExcelUtils.getCell(sh, crb.getFirstRow(), crb.getFirstColumn());
  1276. //System.out.println("value0 "+ExcelUtils.getCellValue(cell));
  1277. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  1278. AreaReference area2 = new AreaReference(cell.getCellFormula());
  1279. evaluator.evaluateInCell(cell);
  1280. CellRangeAddress cra2 = ExcelUtils.mergeArea(sh, area2.getAllReferencedCells()[0]);
  1281. short mergeHeigh = 0;
  1282. for (int row = cra2.getFirstRow(); row <=cra2.getLastRow(); row++)
  1283. mergeHeigh += ExcelUtils.getRow(sh, row).getHeight();
  1284. rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1285. cell = ExcelUtils.getCell(sh, rowNameDataRangeE, cra.getFirstColumn());
  1286. ExcelUtils.paste(sh, cell.getRowIndex(), cell.getColumnIndex(), ExcelUtils.copy(sh, crb));
  1287. cell.getCellStyle().setWrapText(true);
  1288. //RHeight.Rows.AutoFit
  1289. short hCell = ExcelUtils.getRow(sh, cell.getRowIndex()).getHeight();
  1290. AreaReference area3 = new AreaReference(crb.formatAsString());
  1291. if(hCell < mergeHeigh){
  1292. Short h = ExcelUtils.getRowHeight(sh, area3);
  1293. if (h == null) h = 0;
  1294. ExcelUtils.setRowHeight(sh, area3, (short)(h + hCell + mergeHeigh));
  1295. if (wRHidden)
  1296. ExcelUtils.hiddenRows(sh, area3, true);
  1297. }
  1298. ExcelUtils.clear(sh, area3);
  1299. ExcelUtils.clear(sh, new CellReference(cell.getRowIndex(), cell.getColumnIndex()));
  1300. }
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. int i = 1;
  1307. for (int j = keyTotCount - 1; j >= 0; j--)
  1308. if (keyTotGroup[j] > 0){
  1309. if (keyTotGroup[j] == 2){
  1310. //ActiveSheet.Outline.ShowLevels RowLevels:=i
  1311. break;
  1312. }
  1313. i++;
  1314. }
  1315. i = 1;
  1316. for (int j = 0; j<= keyPageCount-1; j++)
  1317. if (keyPageGroup[j] > 0){
  1318. if (keyPageGroup[j] == 2){
  1319. //ActiveSheet.Outline.ShowLevels RowLevels:=i
  1320. break;
  1321. }
  1322. i++;
  1323. }
  1324. // 'сворачивание оутлайнов
  1325. if(pageFormat > 2){
  1326. i = 1;
  1327. for(int j =0; j<=pageFormatCount - 1; j++)
  1328. if(pageFormatGroup[j] > 0 ){
  1329. if (pageFormatGroupHide[j]){
  1330. if (groupYes){
  1331. specHidden(sh, i);
  1332. }else{
  1333. //ActiveSheet.Outline.ShowLevels RowLevels:=i 'при большом количестве строк дает ошибку
  1334. specHidden(sh, i);
  1335. }
  1336. }
  1337. i++;
  1338. }
  1339. }else if(totFormat > 2){
  1340. i = 1;
  1341. for(j =totFormatCount - 1; j>=0; j--)
  1342. if(totFormatGroup[j] > 0){
  1343. if (totFormatGroupHide[j]){
  1344. if (groupYes){
  1345. specHidden(sh, i);
  1346. }else{
  1347. //ActiveSheet.Outline.ShowLevels RowLevels:=i 'при большом количестве строк дает ошибку
  1348. specHidden(sh, i);
  1349. }
  1350. }
  1351. i++;
  1352. }
  1353. }
  1354. }
  1355. private void specHidden(HSSFSheet sh, int hOut){
  1356. int br = 0;
  1357. int er = 0;
  1358. HSSFCell cell = ExcelUtils.find(sh, 0, 0, ExcelUtils.xlMaxNumRow-1, 0,
  1359. 1d, ExcelUtils.xlValues, ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlPrevious);
  1360. if (cell != null)
  1361. br = cell.getRowIndex()+1;
  1362. cell = ExcelUtils.find(sh, 0, 0, ExcelUtils.xlMaxNumRow-1, 0,
  1363. 1d, ExcelUtils.xlValues, ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlNext);
  1364. if (cell != null)
  1365. er = cell.getRowIndex()-1;
  1366. boolean flagB = true;
  1367. k = 1;
  1368. for(int row = br; row <= er; row++){
  1369. /*
  1370. If WorkRange.OutlineLevel > HOut Then
  1371. If FlagB Then
  1372. Set WR = WorkRange: FlagB = False
  1373. Else
  1374. Set WR = Union(WR, WorkRange)
  1375. End If
  1376. K = K + 1
  1377. If K = 1000 Then
  1378. WR.EntireRow.Hidden = True: FlagB = True: K = 1
  1379. End If
  1380. */
  1381. }
  1382. if (k > 1){
  1383. //WR.EntireRow.Hidden = True
  1384. }
  1385. }
  1386. //13, 4 typ's
  1387. private void topPage(HSSFSheet sh) throws JUniPrintException{
  1388. int indexPageSave = wb.getNumberOfSheets();
  1389. wb.createSheet();
  1390. HSSFSheet sheetSave = wb.getSheetAt(indexPageSave);
  1391. ExcelBuffer buffTopPage = null;
  1392. ExcelBuffer buffBottomPage = null;
  1393. if (bottomPageRowB >= 0){
  1394. ExcelBuffer buff = ExcelUtils.copyRows(sh, bottomPageRowB, bottomPageRowB+bottomPageRowE-1);
  1395. ExcelUtils.paste(sheetSave, "A" + (bottomPageRowB+1), buff);
  1396. buffBottomPage = ExcelUtils.copyRows(sheetSave, bottomPageRowB, bottomPageRowB+bottomPageRowE-1);
  1397. }
  1398. if (topPageRowB >= 0){
  1399. ExcelBuffer buff = ExcelUtils.copyRows(sh, topPageRowB, topPageRowB+topPageRowE-1);
  1400. ExcelUtils.paste(sheetSave, "A" + (topPageRowB+1), buff);
  1401. buffTopPage = ExcelUtils.copyRows(sheetSave, topPageRowB, topPageRowB+topPageRowE-1);
  1402. }
  1403. modelDelete(sh);
  1404. //Property[] pr = wb.getSummaryInformation().getProperties();
  1405. // ExcelUtils.breakDownPrintedPage(sh);
  1406. // if(true) return;
  1407. boolean dZeros = sh.isDisplayZeros();
  1408. if (!dZeros) sh.setDisplayZeros(true);
  1409. int rowNameDataPageE = ExcelUtils.getReferanceNameRange(nameDataPageE).getFirstCell().getRow();
  1410. HSSFCell findCell =ExcelUtils.find(sh, 0, 0, rowNameDataPageE, 0, 0d, ExcelUtils.xlValues, ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlNext);
  1411. int row0 = -1, rowP1 = -1;
  1412. if (findCell != null){
  1413. row0 = findCell.getRowIndex();
  1414. for(rowP1 = row0; rowP1 >= 0; rowP1--)
  1415. if (sh.isRowBroken(rowP1)) break;
  1416. }
  1417. if (rowP1 < 1) rowP1 = 1;
  1418. boolean flagHP = false;
  1419. int rowP2 = -1;
  1420. HSSFPrintSetup ps = sh.getPrintSetup();
  1421. float[]sizePage = ExcelUtils.PrintPagesFormat.get(ps.getPaperSize());
  1422. if (sizePage == null) throw new JUniPrintException("Неизвестный формат печатный страницы!");
  1423. float baseSizePage = 0;
  1424. if (ps.getLandscape()) baseSizePage = sizePage[0];
  1425. else baseSizePage = sizePage[1];
  1426. float scale = ps.getScale() / 100;
  1427. double len = baseSizePage -(((ps.getFooterMargin()+ps.getHeaderMargin())*ExcelUtils.Factotr_MM_Inches)+50);
  1428. while(true){
  1429. row0 = -1;
  1430. findCell = ExcelUtils.find(sh, rowP1, 0, rowNameDataPageE, 0, 0d, ExcelUtils.xlValues, ExcelUtils.XlLookAt.xlWhole, ExcelUtils.XlSearchDirection.xlNext);
  1431. if (findCell != null)
  1432. row0 = findCell.getRowIndex();
  1433. if(row0 == -1 || row0 < rowP1) break;
  1434. else{
  1435. if (bottomPageRowB >= 0){
  1436. ExcelUtils.insertRows(sh, row0, bottomPageRowE);
  1437. ExcelUtils.paste(sh, row0, 0, buffBottomPage);
  1438. }
  1439. if (topPageRowB >= 0){
  1440. ExcelUtils.insertRows(sh, row0, topPageRowE);
  1441. ExcelUtils.upadteRowBrokenAfterInsertRows(sh, row0, topPageRowE);
  1442. ExcelUtils.paste(sh, row0, 0, buffTopPage);
  1443. }
  1444. if (rowP2 != -1 && rowP1 > 0) sh.setRowBreak(rowP1);
  1445. int rowNameDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1446. double currSizePage = 0;
  1447. for (rowP2 = row0 + 1; rowP2 <= rowNameDataRangeE; rowP2++){
  1448. HSSFRow hSSFRow = sh.getRow(rowP2);
  1449. if (hSSFRow != null && !hSSFRow.getZeroHeight())
  1450. currSizePage += hSSFRow.getHeightInPoints()*ExcelUtils.Factotr_MM_Points*scale;
  1451. if (currSizePage >= len || sh.isRowBroken(rowP2)){
  1452. // currSizePage = 0;
  1453. // if (!sh.isRowBroken(rowP2)) sh.setRowBreak(rowP2);
  1454. break;
  1455. }
  1456. // if (sh.isRowBroken(rowP2)){
  1457. // sh.removeRowBreak(rowP2);
  1458. // break;
  1459. // }
  1460. }
  1461. rowNameDataPageE = ExcelUtils.getReferanceNameRange(nameDataPageE).getFirstCell().getRow()+1;
  1462. if (rowP2 > rowNameDataPageE) rowP2 = rowNameDataPageE + 1;
  1463. bitch(sh);
  1464. if (topPageRowB >= 0){
  1465. ExcelUtils.replaceRows(sh, row0, row0+topPageRowE, "$"+(detailRowB+1),
  1466. Integer.toString(row0 + topPageRowE + bottomPageRowE), ExcelUtils.xlFormulas,
  1467. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1468. ExcelUtils.replaceRows(sh, row0, row0+topPageRowE, "$"+(detailRowE+1),
  1469. Integer.toString(rowP2), ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart,
  1470. ExcelUtils.XlSearchDirection.xlNext);
  1471. if (topPageColPgNmb >= 0) ExcelUtils.setCellValue( ExcelUtils.getCell(sh, row0 + topPageRowPgNmb, topPageColPgNmb), pgNmb);
  1472. }
  1473. if (bottomPageRowB >= 0){
  1474. ExcelUtils.insertRows(sh, rowP2, bottomPageRowE);
  1475. ExcelUtils.upadteRowBrokenAfterInsertRows(sh, rowP2, bottomPageRowE);
  1476. flagHP = sh.isRowBroken(rowP2);
  1477. ExcelUtils.paste(sh, rowP2, 0, buffBottomPage);
  1478. //видимо из-за толщины линий разделитель иногда убегает вверх
  1479. if (flagHP && !sh.isRowBroken(rowP2)){
  1480. }
  1481. ExcelUtils.replaceRows(sh, rowP2, rowP2+bottomPageRowE, "$"+(detailRowB+1),
  1482. Integer.toString(row0 + topPageRowE + bottomPageRowE), ExcelUtils.xlFormulas,
  1483. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1484. ExcelUtils.replaceRows(sh, rowP2, rowP2+bottomPageRowE, "$"+(detailRowE+1),
  1485. Integer.toString(rowP2), ExcelUtils.xlFormulas,
  1486. ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1487. if (bottomPageColPgNmb >= 0) ExcelUtils.setCellValue( ExcelUtils.getCell(sh, rowP2 + bottomPageRowPgNmb, bottomPageColPgNmb), pgNmb);
  1488. //sh.shiftRows(row0 + topPageRowE-1, sh.getLastRowNum(), -(topPageRowE + bottomPageRowCount+1));
  1489. //ExcelUtils.deleteRow(sh, row0 + topPa geRowE-1);
  1490. for(int row =0; row < bottomPageRowE; row++){
  1491. HSSFRow hSSFRow = ExcelUtils.clearRow(sh, row0 + topPageRowE+row);
  1492. if (hSSFRow!= null) hSSFRow.setZeroHeight(true);
  1493. }
  1494. rowP2 +=bottomPageRowE-1;
  1495. }
  1496. }
  1497. rowP1 = rowP2;
  1498. Object value = ExcelUtils.getCellValue(ExcelUtils.getCell(sh, rowP1, 0));
  1499. if (value != null && value instanceof Double){
  1500. double val = ((Double)value).doubleValue();
  1501. if (val >= 51d && val <= 60d) pgNmb = 1;
  1502. else pgNmb++;
  1503. }
  1504. }
  1505. sh.setDisplayZeros(dZeros);
  1506. wb.removeSheetAt(indexPageSave);
  1507. }
  1508. private void hPCheck(){
  1509. }
  1510. private void model()throws JUniPrintException{
  1511. int typeKeyTot, typeKeyPage;
  1512. int typeFormat, insOutLine;
  1513. int posSer1, posSer2, posSer3;
  1514. int posCom1, posCom2, posBr;
  1515. HSSFSheet activeSheet = null;
  1516. namesMap = ExcelUtils.createNamesMap(wb);
  1517. nameDataBeg = useGeneral? ExcelUtils.getNamedRange(wb, dataBegName): ExcelUtils.getNamedRangeInSheets(namesMap, dataBegName, sheets);
  1518. if (nameDataBeg != null){
  1519. AreaReference areaDataBeg = new AreaReference(nameDataBeg.getRefersToFormula());
  1520. name_WorkSheet = areaDataBeg.getFirstCell().getSheetName();
  1521. activeSheet = wb.getSheet(name_WorkSheet);
  1522. rowWork = areaDataBeg.getFirstCell().getRow();
  1523. }else{
  1524. int activeIndexSheet = wb.getActiveSheetIndex();
  1525. activeSheet = wb.getSheetAt(activeIndexSheet);
  1526. name_WorkSheet = wb.getSheetName(activeIndexSheet);
  1527. rowWork = modelRowE + 1;
  1528. }
  1529. //HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(wb);
  1530. modelColE = ExcelUtils.realLastColumnHide(activeSheet); //Послед.колонка
  1531. lastCol = modelColE;
  1532. nameDataRangeB = ExcelUtils.createNameRange(RANGE_DataRangeB, "'"+name_WorkSheet+"'!$A$"+(rowWork+1), wb);
  1533. rowWork = ExcelUtils.realLastRow(activeSheet)+1;
  1534. int localRow = ExcelUtils.getReferanceNameRange(nameDataRangeB).getFirstCell().getRow();
  1535. if(rowWork < localRow) rowWork = localRow;
  1536. nameDataRangeE = ExcelUtils.createNameRange(RANGE_DataRangeE, "'"+name_WorkSheet+"'!$A$"+(rowWork+1), wb);
  1537. namesMap = ExcelUtils.createNamesMap(wb);
  1538. localRow = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1539. ExcelUtils.setCellValue(ExcelUtils.getCell(activeSheet, localRow, 0), new Double(999));
  1540. ExcelUtils.fillPathRow(activeSheet, localRow, 1, modelColE, "End's", ExcelUtils.xlValues);
  1541. indexPageUniq = 0; headPrimeRowB = -1; headPrimeRowE = 0; headPrimeSeries = "";
  1542. headPrimeDetail = false; headPrimeRowHPageBreak = -1; cellsAutoHeight = "";
  1543. futPrimeRowB = -1; futPrimeRowE = 0; futPrimeRowHPageBreak = -1;
  1544. topPageRowB = -1; topPageRowE = 0; bottomPageRowB = -1; bottomPageRowE = 0;
  1545. headPageRowB = -1; headPageRowE = 0; headPageAfterRow = -1;
  1546. detailRowB = -1; detailRowE = -1; keyTotCount = 0; keyPageCount = 0; addKeyTot = 0;
  1547. groupYes = false;
  1548. formatCol = 0; maxFormat = 0;
  1549. pageFormat = 2; pageFormatCount = 0;
  1550. totFormat = 2; totFormatCount = 0;
  1551. for (int i = 0; i< dimensions; i++){
  1552. keyTotColTest[i] = 0; keyTotRowB[i] = 0; keyTotRowE[i] = 0; keyTotRowD[i] = 0;
  1553. keyPageColTest[i] = 0; keyPageRowB[i] = 0; keyPageRowE[i] = 0; keyPageRowD[i] = 0;
  1554. keyPageSeries[i] = ""; keyPageGroup[i] = 0; keyTotFlagHide[i] = false;
  1555. keyTotModSerP1[i] = ""; keyTotModSerP2[i] = ""; keyTotGroup[i] = 0;
  1556. pageFormatRowB[i] = -1; pageFormatRowE[i] = 0; pageFormatFormula[i] = false;
  1557. pageFormatGroup[i] = 0; pageFormatGroupHide[i] = false;
  1558. totFormatRowB[i] = -1; totFormatRowE[i] = 0; totFormatFormula[i] = false;
  1559. totFormatGroup[i] = 0; totFormatGroupHide[i] = false;
  1560. keyPageSecondRow[i] = false;
  1561. for (int j = 0; j< dimensions2; j++) keyTotColHide[i][j] = "";
  1562. }
  1563. typeKeyTot = 0; typeKeyPage = 0; bottomPageColPgNmb = 0; bottomPageRowPgNmb = 0;
  1564. typeFormat = 0; topPageColPgNmb = 0; topPageRowPgNmb = 0; pgNmb = 1;
  1565. for(int i=0; i<modelRowE; i++){
  1566. HSSFCell cell = ExcelUtils.getCell(activeSheet, i, 0);
  1567. int value = -1;
  1568. switch(cell.getCellType()){
  1569. case HSSFCell.CELL_TYPE_NUMERIC:
  1570. //TODO Дата - это тоже числовой формат. Как её получить?!
  1571. value = (int)cell.getNumericCellValue();
  1572. break;
  1573. case HSSFCell.CELL_TYPE_STRING:
  1574. HSSFRichTextString rich = cell.getRichStringCellValue();
  1575. if (rich != null) value = Integer.parseInt(rich.getString());
  1576. }
  1577. if (value == 0){ //Тип ДЕТАЛЬНОЙ СТРОКИ
  1578. detailRowE = i;
  1579. if(detailRowB == -1) {
  1580. arrCellStyleTextWhiteColor = new HSSFCellStyle[modelColE+1];
  1581. for(int indexCol = 0; indexCol <= modelColE; indexCol++){
  1582. cell = ExcelUtils.getCell(activeSheet, i, indexCol);
  1583. HSSFCellStyle cellStyle = wb.createCellStyle();
  1584. cellStyle.cloneStyleFrom(cell.getCellStyle());
  1585. cellStyle.setFont(fontWhiteColor);
  1586. cellStyle.setBorderTop(HSSFCellStyle.BORDER_NONE);
  1587. cellStyle.setBorderBottom(HSSFCellStyle.BORDER_NONE);
  1588. cellStyle.setWrapText(false);
  1589. arrCellStyleTextWhiteColor[indexCol] = cellStyle;
  1590. }
  1591. detailRowB = i;
  1592. hideDetailRows = ExcelUtils.getRow(activeSheet, i).getZeroHeight();
  1593. System.out.println("hideDetailRows = " + hideDetailRows);
  1594. }
  1595. }else if (value == 1){ //Тип ГЛОБАЛЬНЫЙ ЗАГОЛОВОК
  1596. headPrimeRowE = headPrimeRowE + 1;
  1597. if (headPrimeRowB == -1) {
  1598. headPrimeRowB = i;
  1599. if (headPageRowB == -1) headPageAfterRow = i;
  1600. }
  1601. for (int j=1; j <= modelColE; j++){
  1602. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1603. if (comment != null){
  1604. posSer = 0; posSer1 = 0; posSer2 = 0; posSer3 = 0;
  1605. HSSFRichTextString richTextString = comment.getString();
  1606. if (richTextString != null){
  1607. String textComment = richTextString.getString().toUpperCase();
  1608. posSer = textComment.indexOf(RESWORD_Series.toUpperCase());
  1609. posSer1 = textComment.indexOf(RESWORD_PageFromDetail.toUpperCase());
  1610. posSer2 = textComment.indexOf(RESWORD_HPageBreak.toUpperCase());
  1611. posSer3 = textComment.indexOf(RESWORD_AutoHeight.toUpperCase()+"(");
  1612. int startIndex = posSer + RESWORD_Series.length()+1;
  1613. if(posSer >= 0) {
  1614. headPrimeSeries = textComment.substring(startIndex, startIndex+1).toUpperCase();
  1615. }
  1616. if(posSer1 >= 0) headPrimeDetail = true;
  1617. if(posSer2 >= 0) {
  1618. headPrimeRowHPageBreak = i;
  1619. }
  1620. if(posSer3 >= 0) {
  1621. posBr = textComment.indexOf(")", posSer3);
  1622. cellsAutoHeight = textComment.substring(posSer3+RESWORD_AutoHeight.length()+1, posBr);
  1623. }
  1624. }
  1625. break;
  1626. }
  1627. }
  1628. }else if (value == 2){ //Тип ГЛОБАЛЬНЫЙ КОНЕЦ
  1629. futPrimeRowE = futPrimeRowE + 1;
  1630. if (futPrimeRowB == -1) futPrimeRowB = i;
  1631. for (int j = 1; j<= modelColE; j++){
  1632. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1633. if (comment != null){
  1634. posSer2 = 0;
  1635. HSSFRichTextString richTextString = comment.getString();
  1636. if (richTextString != null){
  1637. String textComment = richTextString.getString().toUpperCase();
  1638. posSer2 = textComment.indexOf(RESWORD_HPageBreak.toUpperCase());
  1639. }
  1640. if (posSer2 >= 0) futPrimeRowHPageBreak = i;
  1641. break;
  1642. }
  1643. }
  1644. searchUniq(activeSheet, i);
  1645. }else if (value == 3){//Тип ВЕРХ СТРАНИЦЫ
  1646. headPageRowE = headPageRowE + 1;
  1647. if (headPageRowB == -1) headPageRowB = i;
  1648. }else if (value == 4){//Тип НИЗ СТРАНИЦЫ
  1649. bottomPageRowE = bottomPageRowE + 1; if(bottomPageRowB == -1) bottomPageRowB = i;
  1650. for (int j = 1; j<= modelColE; j++){
  1651. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1652. if (comment != null){
  1653. bottomPageColPgNmb = j;
  1654. bottomPageRowPgNmb = i - bottomPageRowB;
  1655. }
  1656. }
  1657. }else if (value == 5){//Тип ПУСТАЯ СТРОКА
  1658. }else if (value == 6){//ДОБАВКА К ИТОГАМ ПО КЛЮЧУ
  1659. addKeyTot = i;
  1660. }else if (value == 13){//Тип ВЕРХ СТРАНИЦЫ
  1661. topPageRowE = topPageRowE + 1; if (topPageRowB == -1) topPageRowB = i;
  1662. for (int j = 1; j<= modelColE; j++){
  1663. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1664. if (comment != null){
  1665. topPageColPgNmb = j;
  1666. topPageRowPgNmb = i - topPageRowB;
  1667. }
  1668. }
  1669. }else if (value >= 21 && value <= 40){//Типы ИТОГОВ ПО КЛЮЧУ
  1670. if(typeKeyTot != (int) value){ //Обработка перв.строки
  1671. typeKeyTot = (int) value;
  1672. keyTotRowB[keyTotCount] = i;
  1673. keyTotColTest[keyTotCount] = 1;
  1674. keyTotCount++;
  1675. }
  1676. for (int j = 1; j<= modelColE; j++){
  1677. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1678. if (comment != null){
  1679. posSer = 0; posSer1 = 0; posSer2 = 0; posSer3 = 0;
  1680. HSSFRichTextString richTextString = comment.getString();
  1681. if (richTextString != null){
  1682. String textComment = richTextString.getString().toUpperCase();
  1683. posSer = textComment.indexOf(RESWORD_MultiHide.toUpperCase()+"(");
  1684. posSer1 = textComment.indexOf(RESWORD_ModSer.toUpperCase());
  1685. posSer2 = textComment.indexOf(RESWORD_Group.toUpperCase());
  1686. posSer3 = textComment.indexOf(RESWORD_GroupHide.toUpperCase());
  1687. int startIndex = posSer + RESWORD_Series.length()+1;
  1688. if(posSer >= 0) {
  1689. keyTotFlagHide[keyTotCount - 1] = true;
  1690. k = 0; posCom1 = posSer + RESWORD_MultiHide.length()+1;
  1691. posBr = textComment.indexOf(")", posSer);
  1692. String[] params = textComment.substring(posCom1, posBr).split(",");
  1693. for(int i_params = 0; i_params < params.length; i_params++){
  1694. keyTotColHide[keyTotCount - 1][i_params] = params[i_params];
  1695. }
  1696. }
  1697. if(posSer1 >= 0) {
  1698. posSer = textComment.indexOf(",", posSer1);
  1699. keyTotModSerP1[keyTotCount - 1] = textComment.substring(posSer1+RESWORD_ModSer.length()+1, posSer);
  1700. keyTotModSerP2[keyTotCount - 1] = textComment.substring(posSer+1, textComment.indexOf(")", posSer1));
  1701. }
  1702. if(posSer2 >= 0) {
  1703. keyTotGroup[keyTotCount - 1] = 1;
  1704. }
  1705. if(posSer3 >= 0) keyTotGroup[keyTotCount - 1] = 2;
  1706. }
  1707. keyTotColTest[keyTotCount - 1] = j;
  1708. break;
  1709. }
  1710. }
  1711. keyTotRowE[keyTotCount - 1] += 1;
  1712. }else if (value >= 51 && value <= 70){//Типы ЗАГОЛОВКИ ПО КЛЮЧУ
  1713. //System.out.println("found grouping row with code = " + value);
  1714. if (typeKeyPage != (int) value ){ //Обработка перв.строки
  1715. typeKeyPage = (int) value;
  1716. keyPageRowB[keyPageCount] = i;
  1717. keyPageColTest[keyPageCount] = 2;
  1718. keyPageCount++;
  1719. if (headPageRowB == -1) headPageAfterRow = i;
  1720. }
  1721. for (int j = 1; j<= modelColE; j++){
  1722. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1723. if (comment != null){
  1724. posSer = 0; posSer2 = 0; posSer3 = 0;
  1725. HSSFRichTextString richTextString = comment.getString();
  1726. if (richTextString != null){
  1727. String textComment = richTextString.getString().toUpperCase();
  1728. posSer = textComment.indexOf(RESWORD_Series.toUpperCase());
  1729. posSer2 = textComment.indexOf(RESWORD_Group.toUpperCase());
  1730. posSer3 = textComment.indexOf(RESWORD_GroupHide.toUpperCase());
  1731. if(posSer >= 0) {
  1732. int startIndex = RESWORD_Series.length() + 1;
  1733. keyPageSeries[keyPageCount - 1] = textComment.substring(startIndex, startIndex+1).toUpperCase();
  1734. }
  1735. if(posSer2 >= 0) keyPageGroup[keyPageCount - 1] = 1;
  1736. if(posSer3 >= 0) keyPageGroup[keyPageCount - 1] = 2;
  1737. }
  1738. keyPageColTest[keyPageCount-1] = j;
  1739. break;
  1740. }
  1741. }
  1742. keyPageRowE[keyPageCount - 1] +=1;
  1743. if (value >=51 && value<=60) keyPageRowD[keyPageCount - 1] = 1;
  1744. //System.out.print("keyPageCount = " + keyPageCount + ", keyPageRowB = " + Arrays.deepToString(keyPageRowB) + ", keyPageColTest = " + Arrays.deepToString(keyPageColTest));
  1745. //System.out.print("keyPageSeries = " + Arrays.deepToString(keyPageSeries));
  1746. //System.out.println("keyPageGroup = " + Arrays.deepToString(keyPageGroup));
  1747. }else if (value >= -50 && value <= -41){//Типы ЗАГОЛОВОКИ для ФОРМАТИРОВАНИЯ
  1748. if (typeFormat != (int) value ){ //Обработка перв.строки
  1749. typeFormat = (int) value;
  1750. pageFormatRowB[pageFormatCount] = i;
  1751. pageFormatCount++;
  1752. }
  1753. for (int j = 1; j<= modelColE; j++){
  1754. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1755. if (comment != null){
  1756. posSer2 = 0; posSer3 = 0;
  1757. HSSFRichTextString richTextString = comment.getString();
  1758. if (richTextString != null){
  1759. String textComment = richTextString.getString().toUpperCase();
  1760. posSer2 = textComment.indexOf(RESWORD_Group.toUpperCase());
  1761. posSer3 = textComment.indexOf(RESWORD_GroupHide.toUpperCase());
  1762. if(posSer2 >= 0) {
  1763. pageFormatGroup[pageFormatCount - 1] = pageFormat;
  1764. pageFormat++;
  1765. }
  1766. if(posSer3 >= 0) pageFormatGroupHide[pageFormatCount - 1] = true;
  1767. }
  1768. break;
  1769. }
  1770. }
  1771. if (ExcelUtils.hasFormulaRow(activeSheet, i) == null) pageFormatFormula[pageFormatCount - 1] = true;
  1772. pageFormatRowE[pageFormatCount - 1]++;
  1773. }else if (value >= 41 && value <= 50){//Типы ИТОГИ для ФОРМАТИРОВАНИЯ
  1774. if (typeFormat != (int) value ){ //Обработка перв.строки
  1775. typeFormat = (int) value;
  1776. totFormatRowB[totFormatCount] = i;
  1777. totFormatCount++;
  1778. }
  1779. for (int j = 1; j<= modelColE; j++){
  1780. HSSFComment comment = ExcelUtils.getCell(activeSheet, i, j).getCellComment();
  1781. if (comment != null){
  1782. posSer2 = 0; posSer3 = 0;
  1783. HSSFRichTextString richTextString = comment.getString();
  1784. if (richTextString != null){
  1785. String textComment = richTextString.getString().toUpperCase();
  1786. posSer2 = textComment.indexOf(RESWORD_Group.toUpperCase());
  1787. posSer3 = textComment.indexOf(RESWORD_GroupHide.toUpperCase());
  1788. if(posSer2 >= 0) {
  1789. totFormatGroup[totFormatCount - 1] = totFormat;
  1790. totFormat++;
  1791. }
  1792. if(posSer3 >= 0) {
  1793. totFormatGroupHide[totFormatCount - 1] = true;
  1794. }
  1795. }
  1796. break;
  1797. }
  1798. }
  1799. if (ExcelUtils.hasFormulaRow(activeSheet, i) == null) totFormatFormula[totFormatCount - 1] = true;
  1800. totFormatRowE[totFormatCount - 1]++;
  1801. }else if(value >=100 && value <=200){//Типы пользователя
  1802. }else throw new JUniPrintException("В ОБРАЗЦЕ строка недопустимого типа!");
  1803. }
  1804. //есть группировка в типах для ФОРМАТИРОВАНИЯ, проставляем уровень группировки в колонке группировки
  1805. formatCol = lastCol + 1;
  1806. if (pageFormat > 2 || totFormat > 2){
  1807. // MaxFormat = ActiveSheet.Rows.OutlineLevel
  1808. if (pageFormat > 2){
  1809. maxFormat = pageFormat - 1;
  1810. insOutLine = pageFormat;
  1811. for (int i = pageFormatCount - 1; i >= 0; i--){
  1812. if (pageFormatGroup[i] != 0) insOutLine--;
  1813. if (insOutLine != pageFormat){
  1814. for(int offsetRow = 0; i<pageFormatRowE[i]; offsetRow++)
  1815. ExcelUtils.setCellValue(ExcelUtils.getCell(activeSheet, pageFormatRowB[i]+offsetRow, formatCol), insOutLine);
  1816. j = pageFormatCount - i - 1;
  1817. if (totFormatRowB[j] != 0)
  1818. for(int offsetRow = 0; i<totFormatRowE[j]; offsetRow++)
  1819. ExcelUtils.setCellValue(ExcelUtils.getCell(activeSheet, totFormatRowB[j], formatCol), insOutLine);
  1820. }
  1821. }
  1822. }else{
  1823. maxFormat = totFormat - 1;
  1824. insOutLine = totFormat;
  1825. for(int i = 0; i<=totFormatCount - 1; i++){
  1826. if (totFormatGroup[i] != 0) insOutLine--;
  1827. if (insOutLine != totFormat){
  1828. ExcelUtils.fillPathCol(activeSheet, formatCol, (int)totFormatRowB[i], (int)(totFormatRowB[i]+totFormatRowE[i]-1), insOutLine, ExcelUtils.xlValues);
  1829. int j = totFormatCount - i - 1;
  1830. if (pageFormatRowB[j] != -1)
  1831. ExcelUtils.fillPathCol(activeSheet, formatCol, (int)pageFormatRowB[j], (int)(pageFormatRowB[j]+pageFormatRowE[j]-1), insOutLine, ExcelUtils.xlValues);
  1832. }
  1833. }
  1834. }
  1835. }
  1836. autoHeight(activeSheet);
  1837. for(int i = 0; i<= keyPageCount - 1; i++){ //поиск ссылки на вторую дет.строку
  1838. for(int offsetRow = 0; offsetRow < keyPageRowE[i]; offsetRow++){
  1839. HSSFRow row = ExcelUtils.getRow(activeSheet, keyPageRowB[i]+offsetRow);
  1840. Iterator it = row.cellIterator();
  1841. while(it.hasNext()){
  1842. HSSFCell cell = (HSSFCell)it.next();
  1843. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  1844. String formula = cell.getCellFormula();
  1845. if (formula != null && formula.indexOf("$"+detailRowE)>=0){
  1846. keyPageSecondRow[i] = true;
  1847. break;
  1848. }
  1849. }
  1850. }
  1851. if(keyPageSecondRow[i]) break;
  1852. }
  1853. }
  1854. if(detailRowE - detailRowB > 1) throw new JUniPrintException("В ОБРАЗЦЕ больше двух строк с кодом 0!");
  1855. for(int indexRow = 0; indexRow < modelRowE; indexRow++){
  1856. HSSFRow row = ExcelUtils.getRow(activeSheet, indexRow);
  1857. Iterator it = row.cellIterator();
  1858. while(it.hasNext()) ((HSSFCell)it.next()).setCellComment(null);
  1859. }
  1860. }
  1861. private void autoHeight(HSSFSheet activeSheet){
  1862. double mergeWidth;
  1863. HSSFCellStyle defaultCellStyle = wb.createCellStyle();
  1864. if (!cellsAutoHeight.isEmpty()){
  1865. String[] arrCellAH = cellsAutoHeight.split(",");
  1866. for(String cellAH: arrCellAH){
  1867. //if (cellAH.equals("B4")) continue;
  1868. AreaReference cellAHRef = new AreaReference(cellAH);
  1869. if(cellAHRef.isSingleCell() && ExcelUtils.getCell(activeSheet, cellAHRef.getFirstCell().getRow(), cellAHRef.getFirstCell().getCol()).getCellStyle().getWrapText()){
  1870. CellRangeAddress workMergeRef = ExcelUtils.mergeArea(activeSheet, cellAHRef.getFirstCell());
  1871. mergeWidth = 0;
  1872. for(int col=workMergeRef.getFirstColumn(); col <=workMergeRef.getLastColumn(); col++){
  1873. mergeWidth += activeSheet.getColumnWidth(col)+ 0.353*FACTOR_PIXEL_TO_EXCEL;
  1874. }
  1875. activeSheet.setColumnWidth(++lastCol, (int)mergeWidth);
  1876. //ExcelUtils.paste(activeSheet, ExcelUtils.xlc(lastCol + 2)+(cellAHRef.getFirstCell().getRow()+1), ExcelUtils.copy(activeSheet, workMergeRef), ExcelUtils.xlFormats);
  1877. ExcelUtils.paste(activeSheet, cellAHRef.getFirstCell().getRow(), lastCol + 1, ExcelUtils.copy(activeSheet, workMergeRef), ExcelUtils.xlFormats);
  1878. CellRangeAddress workMergeRef1 = ExcelUtils.mergeArea(activeSheet, new CellReference(cellAHRef.getFirstCell().getRow(), lastCol + 1));
  1879. //System.out.println("workMergeRef1 "+ workMergeRef1.formatAsString());
  1880. for(int i =0; i<activeSheet.getNumMergedRegions(); i++)
  1881. if(activeSheet.getMergedRegion(i).equals(workMergeRef1)){
  1882. activeSheet.removeMergedRegion(i);
  1883. break;
  1884. }
  1885. HSSFCell srcCell = ExcelUtils.getCell(activeSheet, workMergeRef1.getFirstRow(), workMergeRef1.getFirstColumn());
  1886. HSSFCell distCell = ExcelUtils.getCell(activeSheet, cellAHRef.getFirstCell().getRow(), lastCol);
  1887. ExcelUtils.setCellValue(distCell, ExcelUtils.getCellValue(srcCell));
  1888. distCell.getCellStyle().cloneStyleFrom(srcCell.getCellStyle());
  1889. for(int row=workMergeRef1.getFirstRow(); row <=workMergeRef1.getLastRow(); row++)
  1890. for(int col=workMergeRef1.getFirstColumn(); col <=workMergeRef1.getLastColumn(); col++)
  1891. ExcelUtils.getCell(activeSheet, row, col).setCellStyle(defaultCellStyle);
  1892. activeSheet.setColumnHidden(lastCol, true);
  1893. //distCell.getCellStyle().setDataFormat((short)0);
  1894. if (workMergeRef.getLastRow()-workMergeRef.getFirstRow() > 0 ||
  1895. workMergeRef.getLastColumn()-workMergeRef.getFirstColumn() > 0){
  1896. distCell.setCellFormula(cellAHRef.getFirstCell().formatAsString());
  1897. }
  1898. else
  1899. distCell.setCellFormula("\".\"");
  1900. if (workMergeRef.getLastRow()-workMergeRef.getFirstRow() > 0 ){
  1901. HSSFCellStyle defaultCellStyle2 = wb.createCellStyle();
  1902. defaultCellStyle2.cloneStyleFrom(distCell.getCellStyle());
  1903. defaultCellStyle2.setWrapText(false);
  1904. distCell.setCellStyle(defaultCellStyle2);
  1905. //distCell.getCellStyle().setWrapText(false);
  1906. if (hideFewRow == null) hideFewRow = new ArrayList<AreaReference>();
  1907. hideFewRow.add(new AreaReference(new CellReference(0, lastCol), new CellReference(ExcelUtils.xlMaxNumRow-1, lastCol)));
  1908. }else{
  1909. if (hideOneRow == null) hideOneRow = new ArrayList<AreaReference>();
  1910. hideOneRow.add(new AreaReference(new CellReference(0, lastCol), new CellReference(ExcelUtils.xlMaxNumRow-1, lastCol)));
  1911. }
  1912. }
  1913. }
  1914. }
  1915. }
  1916. //Поиск Uniq(X:X) и построение уникальных списков
  1917. private void searchUniq(HSSFSheet activeSheet, int currRow){
  1918. String unF;
  1919. int unLast;
  1920. if (nameDataRangeB == null || nameDataRangeE == null){
  1921. Map<String, Map<String, HSSFName>> namesMap = ExcelUtils.createNamesMap(wb);
  1922. nameDataRangeB = ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_DataRangeB, new String[]{name_WorkSheet});
  1923. nameDataRangeE = ExcelUtils.getNamedRangeInSheets(namesMap, RANGE_DataRangeE, new String[]{name_WorkSheet});
  1924. }
  1925. int rowDataRangeB = ExcelUtils.getReferanceNameRange(nameDataRangeB).getFirstCell().getRow();
  1926. int rowDataRangeE = ExcelUtils.getReferanceNameRange(nameDataRangeE).getFirstCell().getRow();
  1927. for(int j = 1; j <= modelColE; j++){
  1928. HSSFCell cell = ExcelUtils.getCell(activeSheet, currRow, j);
  1929. if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  1930. String formula = cell.getCellFormula();
  1931. if (formula != null && !formula.isEmpty()){
  1932. posSer = formula.indexOf(RESWORD_Uniq+"(");
  1933. //Есть "uniq(" и есть детальные строки
  1934. if(posSer >= 0 && rowDataRangeB != rowDataRangeE){
  1935. if (indexPageUniq == 0){
  1936. // Name_WorkSheet = ActiveSheet.Name
  1937. wb.createSheet();
  1938. indexPageUniq = wb.getNumberOfSheets()-1;
  1939. // Worksheets(Name_WorkSheet).Activate
  1940. }
  1941. int begPos = posSer + RESWORD_Uniq.length()+1;
  1942. unC = formula.substring(begPos, formula.indexOf(":")); //определить колонку
  1943. unF = formula.substring(posSer, formula.indexOf(")")+1);
  1944. int numUnC = CellReference.convertColStringToIndex(unC);
  1945. ExcelUtils.setCellValue(ExcelUtils.getCell(activeSheet, rowDataRangeB-1, numUnC), unF);
  1946. ExcelUtils.replace(activeSheet, rowDataRangeB-1, numUnC, rowDataRangeE, numUnC, "\"", "'", ExcelUtils.xlFormulas, ExcelUtils.XlLookAt.xlPart, ExcelUtils.XlSearchDirection.xlNext);
  1947. List<CellValue> list = new ArrayList<CellValue>();
  1948. for(int row=rowDataRangeB-1; row<=rowDataRangeE;row++){
  1949. cell = ExcelUtils.getCell(activeSheet, row, numUnC);
  1950. CellValue obj = new CellValue(ExcelUtils.getCellValue(cell));
  1951. if (list.indexOf(obj) < 0) list.add(obj);
  1952. }
  1953. unLast = list.size();
  1954. HSSFSheet sheetUniq = wb.getSheetAt(indexPageUniq);
  1955. ExcelUtils.setCellValue(ExcelUtils.getCell(sheetUniq, 0, numUnC), unLast);
  1956. int indexRow = 1;
  1957. for(CellValue obj:list){
  1958. ExcelUtils.setCellValue(ExcelUtils.getCell(sheetUniq, indexRow++, numUnC), obj.getValue());
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. }
  1965. }