OrdersExcelExportOfTemplateUtil.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com)
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package cn.com.lzt.common.util;
  17. import org.apache.commons.lang3.StringUtils;
  18. import org.apache.poi.ss.usermodel.*;
  19. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  20. import org.jeecgframework.poi.cache.ExcelCache;
  21. import org.jeecgframework.poi.excel.annotation.ExcelTarget;
  22. import org.jeecgframework.poi.excel.entity.TemplateExportParams;
  23. import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
  24. import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
  25. import org.jeecgframework.poi.excel.entity.params.ExcelTemplateParams;
  26. import org.jeecgframework.poi.excel.export.base.ExcelExportBase;
  27. import org.jeecgframework.poi.excel.export.styler.IExcelExportStyler;
  28. import org.jeecgframework.poi.exception.excel.ExcelExportException;
  29. import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum;
  30. import org.jeecgframework.poi.util.PoiPublicUtil;
  31. import org.jeecgframework.poi.util.PoiSheetUtility;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import java.lang.reflect.Field;
  35. import java.util.*;
  36. import static org.jeecgframework.poi.util.PoiElUtil.*;
  37. /**
  38. * Excel 瀵煎嚭鏍规嵁妯℃澘瀵煎嚭
  39. *
  40. * @author JueYue
  41. * @date 2013-10-17
  42. * @version 1.0
  43. */
  44. public final class OrdersExcelExportOfTemplateUtil extends ExcelExportBase {
  45. private static final Logger LOGGER = LoggerFactory.getLogger(OrdersExcelExportOfTemplateUtil.class);
  46. /**
  47. * 缂撳瓨TEMP 鐨刦or each鍒涘缓鐨刢ell ,璺宠繃杩欎釜cell鐨勬ā鏉胯娉曟煡鎵�,鎻愰珮鏁堢巼
  48. */
  49. private Set<String> tempCreateCellSet = new HashSet<String>();
  50. /**
  51. * 妯℃澘鍙傛暟,鍏ㄥ眬閮界敤鍒�
  52. */
  53. private TemplateExportParams teplateParams;
  54. /**
  55. * 寰�Sheet 濉厖姝e父鏁版嵁,鏍规嵁琛ㄥご淇℃伅 浣跨敤瀵煎叆鐨勯儴鍒嗛�昏緫,鍧愬璞℃槧灏�
  56. *
  57. * @param pojoClass
  58. * @param dataSet
  59. * @param workbook
  60. */
  61. private void addDataToSheet(Class<?> pojoClass, Collection<?> dataSet, Sheet sheet, Workbook workbook) throws Exception {
  62. if (workbook instanceof XSSFWorkbook) {
  63. super.type = ExcelType.XSSF;
  64. }
  65. // 鑾峰彇琛ㄥご鏁版嵁
  66. Map<String, Integer> titlemap = getTitleMap(sheet);
  67. Drawing patriarch = sheet.createDrawingPatriarch();
  68. // 寰楀埌鎵�鏈夊瓧娈�
  69. Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
  70. ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);
  71. String targetId = null;
  72. if (etarget != null) {
  73. targetId = etarget.value();
  74. }
  75. // 鑾峰彇瀹炰綋瀵硅薄鐨勫鍑烘暟鎹�
  76. List<ExcelExportEntity> excelParams = new ArrayList<ExcelExportEntity>();
  77. getAllExcelField(null, targetId, fileds, excelParams, pojoClass, null);
  78. // 鏍规嵁琛ㄥご杩涜绛涢�夋帓搴�
  79. sortAndFilterExportField(excelParams, titlemap);
  80. short rowHeight = getRowHeight(excelParams);
  81. int index = teplateParams.getHeadingRows() + teplateParams.getHeadingStartRow(), titleHeight = index;
  82. // 涓嬬Щ鏁版嵁,妯℃嫙鎻掑叆
  83. //sheet.shiftRows(teplateParams.getHeadingRows() + teplateParams.getHeadingStartRow(), sheet.getLastRowNum(), getShiftRows(dataSet, excelParams), true, true);
  84. if (excelParams.size() == 0) {
  85. return;
  86. }
  87. Iterator<?> its = dataSet.iterator();
  88. while (its.hasNext()) {
  89. Object t = its.next();
  90. index += createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight);
  91. }
  92. // 鍚堝苟鍚岀被椤�
  93. mergeCells(sheet, excelParams, titleHeight);
  94. }
  95. /**
  96. * 涓嬬Щ鏁版嵁
  97. *
  98. * @param excelParams
  99. * @return
  100. */
  101. private int getShiftRows(Collection<?> dataSet, List<ExcelExportEntity> excelParams) throws Exception {
  102. int size = 0;
  103. Iterator<?> its = dataSet.iterator();
  104. while (its.hasNext()) {
  105. Object t = its.next();
  106. size += getOneObjectSize(t, excelParams);
  107. }
  108. return size;
  109. }
  110. /**
  111. * 鑾峰彇鍗曚釜瀵硅薄鐨勯珮搴�,涓昏鏄鐞嗕竴鍫嗗鐨勬儏鍐�
  112. *
  113. * @param t
  114. * @param excelParams
  115. * @throws Exception
  116. */
  117. public int getOneObjectSize(Object t, List<ExcelExportEntity> excelParams) throws Exception {
  118. ExcelExportEntity entity;
  119. int maxHeight = 1;
  120. for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
  121. entity = excelParams.get(k);
  122. if (entity.getList() != null) {
  123. Collection<?> list = (Collection<?>) entity.getMethod().invoke(t, new Object[] {});
  124. if (list != null && list.size() > maxHeight) {
  125. maxHeight = list.size();
  126. }
  127. }
  128. }
  129. return maxHeight;
  130. }
  131. public Workbook createExcleByTemplate(TemplateExportParams params, Class<?> pojoClass, Collection<?> dataSet, Map<String, Object> map) {
  132. // step 1. 鍒ゆ柇妯℃澘鐨勫湴鍧�
  133. if (params == null || map == null || StringUtils.isEmpty(params.getTemplateUrl())) {
  134. throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
  135. }
  136. Workbook wb = null;
  137. // step 2. 鍒ゆ柇妯℃澘鐨凟xcel绫诲瀷,瑙f瀽妯℃澘
  138. try {
  139. this.teplateParams = params;
  140. wb = getCloneWorkBook();
  141. // 鍒涘缓琛ㄦ牸鏍峰紡
  142. setExcelExportStyler((IExcelExportStyler) teplateParams.getStyle().getConstructor(Workbook.class).newInstance(wb));
  143. // step 3. 瑙f瀽妯℃澘
  144. for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets() : params.getSheetNum().length; i < le; i++) {
  145. if (params.getSheetName() != null && params.getSheetName().length > i && StringUtils.isNotEmpty(params.getSheetName()[i])) {
  146. wb.setSheetName(i, params.getSheetName()[i]);
  147. }
  148. tempCreateCellSet.clear();
  149. parseTemplate(wb.getSheetAt(i), map);
  150. }
  151. if (dataSet != null) {
  152. // step 4. 姝e父鐨勬暟鎹~鍏�
  153. dataHanlder = params.getDataHanlder();
  154. if (dataHanlder != null) {
  155. needHanlderList = Arrays.asList(dataHanlder.getNeedHandlerFields());
  156. }
  157. addDataToSheet(pojoClass, dataSet, wb.getSheetAt(params.getDataSheetNum()), wb);
  158. }
  159. } catch (Exception e) {
  160. LOGGER.error(e.getMessage(), e);
  161. return null;
  162. }
  163. return wb;
  164. }
  165. /**
  166. * 鍏嬮殕excel闃叉鎿嶄綔鍘熷璞�,workbook鏃犳硶鍏嬮殕,鍙兘瀵筫xcel杩涜鍏嬮殕
  167. *
  168. * @throws Exception
  169. * @Author JueYue
  170. * @date 2013-11-11
  171. */
  172. private Workbook getCloneWorkBook() throws Exception {
  173. return ExcelCache.getWorkbook(teplateParams.getTemplateUrl(), teplateParams.getSheetNum(), teplateParams.isScanAllsheet());
  174. }
  175. /**
  176. * 鑾峰彇琛ㄥご鏁版嵁,璁剧疆琛ㄥご鐨勫簭鍙�
  177. *
  178. * @param sheet
  179. * @return
  180. */
  181. private Map<String, Integer> getTitleMap(Sheet sheet) {
  182. Row row = null;
  183. Iterator<Cell> cellTitle;
  184. Map<String, Integer> titlemap = new HashMap<String, Integer>();
  185. for (int j = 0; j < teplateParams.getHeadingRows(); j++) {
  186. row = sheet.getRow(j + teplateParams.getHeadingStartRow());
  187. cellTitle = row.cellIterator();
  188. int i = row.getFirstCellNum();
  189. while (cellTitle.hasNext()) {
  190. Cell cell = cellTitle.next();
  191. String value = cell.getStringCellValue();
  192. if (!StringUtils.isEmpty(value)) {
  193. titlemap.put(value, i);
  194. }
  195. i = i + 1;
  196. }
  197. }
  198. return titlemap;
  199. }
  200. private void parseTemplate(Sheet sheet, Map<String, Object> map) throws Exception {
  201. deleteCell(sheet, map);
  202. Row row = null;
  203. int index = 0;
  204. while (index <= sheet.getLastRowNum()) {
  205. row = sheet.getRow(index++);
  206. if (row == null) {
  207. continue;
  208. }
  209. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
  210. if (row.getCell(i) != null && !tempCreateCellSet.contains(row.getRowNum() + "_" + row.getCell(i).getColumnIndex())) {
  211. setValueForCellByMap(row.getCell(i), map);
  212. }
  213. }
  214. }
  215. }
  216. /**
  217. * 鍏堝垽鏂垹闄�,鐪佸緱褰卞搷鏁堢巼
  218. *
  219. * @param sheet
  220. * @param map
  221. * @throws Exception
  222. */
  223. private void deleteCell(Sheet sheet, Map<String, Object> map) throws Exception {
  224. Row row = null;
  225. Cell cell = null;
  226. int index = 0;
  227. while (index <= sheet.getLastRowNum()) {
  228. row = sheet.getRow(index++);
  229. if (row == null) {
  230. continue;
  231. }
  232. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
  233. cell = row.getCell(i);
  234. if (row.getCell(i) != null && (cell.getCellType() == CellType.STRING || cell.getCellType() == CellType.NUMERIC)) {
  235. cell.setCellType(CellType.STRING);
  236. String text = cell.getStringCellValue();
  237. if (text.contains(IF_DELETE)) {
  238. if (Boolean.valueOf(eval(text.substring(text.indexOf(START_STR) + 2, text.indexOf(END_STR)).trim(), map).toString())) {
  239. PoiSheetUtility.deleteColumn(sheet, i);
  240. }
  241. cell.setCellValue("");
  242. }
  243. }
  244. }
  245. }
  246. }
  247. /**
  248. * 缁欐瘡涓狢ell閫氳繃瑙f瀽鏂瑰紡set鍊�
  249. *
  250. * @param cell
  251. * @param map
  252. */
  253. private void setValueForCellByMap(Cell cell, Map<String, Object> map) throws Exception {
  254. CellType cellType = cell.getCellType();
  255. if (cellType != CellType.STRING && cellType != CellType.NUMERIC) {
  256. return;
  257. }
  258. String oldString;
  259. cell.setCellType(CellType.STRING);
  260. oldString = cell.getStringCellValue();
  261. if (oldString != null && oldString.indexOf(START_STR) != -1 && !oldString.contains(FOREACH)) {
  262. // step 2. 鍒ゆ柇鏄惁鍚湁瑙f瀽鍑芥暟
  263. String params = null;
  264. boolean isNumber = false;
  265. if (isNumber(oldString)) {
  266. isNumber = true;
  267. oldString = oldString.replace(NUMBER_SYMBOL, "");
  268. }
  269. while (oldString.indexOf(START_STR) != -1) {
  270. params = oldString.substring(oldString.indexOf(START_STR) + 2, oldString.indexOf(END_STR));
  271. oldString = oldString.replace(START_STR + params + END_STR, eval(params, map).toString());
  272. }
  273. // 濡備綍鏄暟鍊� 绫诲瀷,灏辨寜鐓ф暟鍊肩被鍨嬭繘琛岃缃�
  274. if (isNumber && StringUtils.isNotBlank(oldString)) {
  275. cell.setCellValue(Double.parseDouble(oldString));
  276. cell.setCellType(CellType.NUMERIC);
  277. } else {
  278. cell.setCellValue(oldString);
  279. }
  280. }
  281. // 鍒ゆ柇foreach 杩欑鏂规硶
  282. if (oldString != null && oldString.contains(FOREACH)) {
  283. addListDataToExcel(cell, map, oldString.trim());
  284. }
  285. }
  286. private boolean isNumber(String text) {
  287. return text.startsWith(NUMBER_SYMBOL) || text.contains("{" + NUMBER_SYMBOL) || text.contains(" " + NUMBER_SYMBOL);
  288. }
  289. /**
  290. * 鍒╃敤foreach寰幆杈撳嚭鏁版嵁
  291. *
  292. * @param cell
  293. * @param map
  294. * @throws Exception
  295. */
  296. private void addListDataToExcel(Cell cell, Map<String, Object> map, String name) throws Exception {
  297. boolean isCreate = !name.contains(FOREACH_NOT_CREATE);
  298. boolean isShift = name.contains(FOREACH_AND_SHIFT);
  299. name = name.replace(FOREACH_NOT_CREATE, EMPTY).replace(FOREACH_AND_SHIFT, EMPTY).replace(FOREACH, EMPTY).replace(START_STR, EMPTY);
  300. String[] keys = name.replaceAll("\\s{1,}", " ").trim().split(" ");
  301. Collection<?> datas = (Collection<?>) PoiPublicUtil.getParamsValue(keys[0], map);
  302. List<ExcelTemplateParams> columns = getAllDataColumns(cell, name.replace(keys[0], EMPTY));
  303. if (datas == null) {
  304. return;
  305. }
  306. Iterator<?> its = datas.iterator();
  307. Row row;
  308. int rowIndex = cell.getRow().getRowNum() + 1;
  309. // 澶勭悊褰撳墠琛�
  310. if (its.hasNext()) {
  311. Object t = its.next();
  312. cell.getRow().setHeight(columns.get(0).getHeight());
  313. setForEeachCellValue(isCreate, cell.getRow(), cell.getColumnIndex(), t, columns, map);
  314. }
  315. if (isShift) {
  316. cell.getRow().getSheet().shiftRows(cell.getRowIndex() + 1, cell.getRow().getSheet().getLastRowNum(), datas.size() - 1, true, true);
  317. }
  318. while (its.hasNext()) {
  319. Object t = its.next();
  320. if (isCreate) {
  321. row = cell.getRow().getSheet().createRow(rowIndex++);
  322. } else {
  323. row = cell.getRow().getSheet().getRow(rowIndex++);
  324. if (row == null) {
  325. row = cell.getRow().getSheet().createRow(rowIndex - 1);
  326. }
  327. }
  328. row.setHeight(columns.get(0).getHeight());
  329. setForEeachCellValue(isCreate, row, cell.getColumnIndex(), t, columns, map);
  330. }
  331. }
  332. private void setForEeachCellValue(boolean isCreate, Row row, int columnIndex, Object t, List<ExcelTemplateParams> columns, Map<String, Object> map) throws Exception {
  333. for (int i = 0, max = columnIndex + columns.size(); i < max; i++) {
  334. if (row.getCell(i) == null)
  335. row.createCell(i);
  336. }
  337. for (int i = 0, max = columns.size(); i < max; i++) {
  338. boolean isNumber = false;
  339. String tempStr = new String(columns.get(i).getName());
  340. if (isNumber(tempStr)) {
  341. isNumber = true;
  342. tempStr = tempStr.replace(NUMBER_SYMBOL, "");
  343. }
  344. map.put(teplateParams.getTempParams(), t);
  345. String val = eval(tempStr, map).toString();
  346. if (isNumber && StringUtils.isNotEmpty(val)) {
  347. row.getCell(i + columnIndex).setCellValue(Double.parseDouble(val));
  348. row.getCell(i + columnIndex).setCellType(CellType.NUMERIC);
  349. } else {
  350. row.getCell(i + columnIndex).setCellValue(val);
  351. }
  352. row.getCell(i + columnIndex).setCellStyle(columns.get(i).getCellStyle());
  353. tempCreateCellSet.add(row.getRowNum() + "_" + (i + columnIndex));
  354. }
  355. }
  356. /**
  357. * 鑾峰彇杩唬鐨勬暟鎹殑鍊�
  358. *
  359. * @param cell
  360. * @param name
  361. * @return
  362. */
  363. private List<ExcelTemplateParams> getAllDataColumns(Cell cell, String name) {
  364. List<ExcelTemplateParams> columns = new ArrayList<ExcelTemplateParams>();
  365. cell.setCellValue("");
  366. if (name.contains(END_STR)) {
  367. columns.add(new ExcelTemplateParams(name.replace(END_STR, EMPTY).trim(), cell.getCellStyle(), cell.getRow().getHeight()));
  368. return columns;
  369. }
  370. columns.add(new ExcelTemplateParams(name.trim(), cell.getCellStyle(), cell.getRow().getHeight()));
  371. int index = cell.getColumnIndex();
  372. Cell tempCell;
  373. while (true) {
  374. tempCell = cell.getRow().getCell(++index);
  375. if (tempCell == null) {
  376. break;
  377. }
  378. String cellStringString;
  379. try {// 鍏佽涓虹┖,鍗曡〃绀哄凡缁忓畬缁撲簡,鍥犱负鍙兘琚垹闄や簡
  380. cellStringString = tempCell.getStringCellValue();
  381. if (StringUtils.isBlank(cellStringString)) {
  382. break;
  383. }
  384. } catch (Exception e) {
  385. throw new ExcelExportException("for each 褰撲腑瀛樺湪绌哄瓧绗︿覆,璇锋鏌ユā鏉�");
  386. }
  387. // 鎶婅鍙栬繃鐨刢ell 缃负绌�
  388. tempCell.setCellValue("");
  389. if (cellStringString.contains(END_STR)) {
  390. columns.add(new ExcelTemplateParams(cellStringString.trim().replace(END_STR, ""), tempCell.getCellStyle(), tempCell.getRow().getHeight()));
  391. break;
  392. } else {
  393. if (cellStringString.trim().contains(teplateParams.getTempParams())) {
  394. columns.add(new ExcelTemplateParams(cellStringString.trim(), tempCell.getCellStyle(), tempCell.getRow().getHeight()));
  395. } else {
  396. // 鏈�鍚庝竴琛岃鍒犻櫎浜�
  397. break;
  398. }
  399. }
  400. }
  401. return columns;
  402. }
  403. /**
  404. * 瀵瑰鍑哄簭鍒楄繘琛屾帓搴忓拰濉為��
  405. *
  406. * @param excelParams
  407. * @param titlemap
  408. * @return
  409. */
  410. private void sortAndFilterExportField(List<ExcelExportEntity> excelParams, Map<String, Integer> titlemap) {
  411. for (int i = excelParams.size() - 1; i >= 0; i--) {
  412. if (excelParams.get(i).getList() != null && excelParams.get(i).getList().size() > 0) {
  413. sortAndFilterExportField(excelParams.get(i).getList(), titlemap);
  414. if (excelParams.get(i).getList().size() == 0) {
  415. excelParams.remove(i);
  416. } else {
  417. excelParams.get(i).setOrderNum(i);
  418. }
  419. } else {
  420. if (titlemap.containsKey(excelParams.get(i).getName())) {
  421. excelParams.get(i).setOrderNum(i);
  422. } else {
  423. excelParams.remove(i);
  424. }
  425. }
  426. }
  427. sortAllParams(excelParams);
  428. }
  429. }