ExcelUtil.java 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. package com.ruoyi.common.utils.poi;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.lang.reflect.Field;
  8. import java.lang.reflect.Method;
  9. import java.lang.reflect.ParameterizedType;
  10. import java.math.BigDecimal;
  11. import java.text.DecimalFormat;
  12. import java.time.LocalDate;
  13. import java.time.LocalDateTime;
  14. import java.util.ArrayList;
  15. import java.util.Arrays;
  16. import java.util.Collection;
  17. import java.util.Comparator;
  18. import java.util.Date;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import java.util.UUID;
  24. import java.util.stream.Collectors;
  25. import javax.servlet.http.HttpServletResponse;
  26. import org.apache.commons.lang3.ArrayUtils;
  27. import org.apache.commons.lang3.RegExUtils;
  28. import org.apache.commons.lang3.reflect.FieldUtils;
  29. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  30. import org.apache.poi.hssf.usermodel.HSSFPicture;
  31. import org.apache.poi.hssf.usermodel.HSSFPictureData;
  32. import org.apache.poi.hssf.usermodel.HSSFShape;
  33. import org.apache.poi.hssf.usermodel.HSSFSheet;
  34. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  35. import org.apache.poi.ooxml.POIXMLDocumentPart;
  36. import org.apache.poi.ss.usermodel.BorderStyle;
  37. import org.apache.poi.ss.usermodel.Cell;
  38. import org.apache.poi.ss.usermodel.CellStyle;
  39. import org.apache.poi.ss.usermodel.CellType;
  40. import org.apache.poi.ss.usermodel.ClientAnchor;
  41. import org.apache.poi.ss.usermodel.DataFormat;
  42. import org.apache.poi.ss.usermodel.DataValidation;
  43. import org.apache.poi.ss.usermodel.DataValidationConstraint;
  44. import org.apache.poi.ss.usermodel.DataValidationHelper;
  45. import org.apache.poi.ss.usermodel.DateUtil;
  46. import org.apache.poi.ss.usermodel.Drawing;
  47. import org.apache.poi.ss.usermodel.FillPatternType;
  48. import org.apache.poi.ss.usermodel.Font;
  49. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  50. import org.apache.poi.ss.usermodel.IndexedColors;
  51. import org.apache.poi.ss.usermodel.Name;
  52. import org.apache.poi.ss.usermodel.PictureData;
  53. import org.apache.poi.ss.usermodel.Row;
  54. import org.apache.poi.ss.usermodel.Sheet;
  55. import org.apache.poi.ss.usermodel.VerticalAlignment;
  56. import org.apache.poi.ss.usermodel.Workbook;
  57. import org.apache.poi.ss.usermodel.WorkbookFactory;
  58. import org.apache.poi.ss.util.CellRangeAddress;
  59. import org.apache.poi.ss.util.CellRangeAddressList;
  60. import org.apache.poi.util.IOUtils;
  61. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  62. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  63. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  64. import org.apache.poi.xssf.usermodel.XSSFDrawing;
  65. import org.apache.poi.xssf.usermodel.XSSFPicture;
  66. import org.apache.poi.xssf.usermodel.XSSFShape;
  67. import org.apache.poi.xssf.usermodel.XSSFSheet;
  68. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  69. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  70. import org.slf4j.Logger;
  71. import org.slf4j.LoggerFactory;
  72. import com.ruoyi.common.annotation.Excel;
  73. import com.ruoyi.common.annotation.Excel.ColumnType;
  74. import com.ruoyi.common.annotation.Excel.Type;
  75. import com.ruoyi.common.annotation.Excels;
  76. import com.ruoyi.common.config.RuoYiConfig;
  77. import com.ruoyi.common.core.domain.AjaxResult;
  78. import com.ruoyi.common.core.text.Convert;
  79. import com.ruoyi.common.exception.UtilException;
  80. import com.ruoyi.common.utils.DateUtils;
  81. import com.ruoyi.common.utils.DictUtils;
  82. import com.ruoyi.common.utils.StringUtils;
  83. import com.ruoyi.common.utils.file.FileTypeUtils;
  84. import com.ruoyi.common.utils.file.FileUtils;
  85. import com.ruoyi.common.utils.file.ImageUtils;
  86. import com.ruoyi.common.utils.reflect.ReflectUtils;
  87. /**
  88. * Excel相关处理
  89. *
  90. * @author ruoyi
  91. */
  92. public class ExcelUtil<T>
  93. {
  94. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  95. public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
  96. public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
  97. /**
  98. * 用于dictType属性数据存储,避免重复查缓存
  99. */
  100. public Map<String, String> sysDictMap = new HashMap<String, String>();
  101. /**
  102. * Excel sheet最大行数,默认65536
  103. */
  104. public static final int sheetSize = 65536;
  105. /**
  106. * 工作表名称
  107. */
  108. private String sheetName;
  109. /**
  110. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  111. */
  112. private Type type;
  113. /**
  114. * 工作薄对象
  115. */
  116. private Workbook wb;
  117. /**
  118. * 工作表对象
  119. */
  120. private Sheet sheet;
  121. /**
  122. * 样式列表
  123. */
  124. private Map<String, CellStyle> styles;
  125. /**
  126. * 导入导出数据列表
  127. */
  128. private List<T> list;
  129. /**
  130. * 注解列表
  131. */
  132. private List<Object[]> fields;
  133. /**
  134. * 当前行号
  135. */
  136. private int rownum;
  137. /**
  138. * 标题
  139. */
  140. private String title;
  141. /**
  142. * 最大高度
  143. */
  144. private short maxHeight;
  145. /**
  146. * 合并后最后行数
  147. */
  148. private int subMergedLastRowNum = 0;
  149. /**
  150. * 合并后开始行数
  151. */
  152. private int subMergedFirstRowNum = 1;
  153. /**
  154. * 对象的子列表方法
  155. */
  156. private Method subMethod;
  157. /**
  158. * 对象的子列表属性
  159. */
  160. private List<Field> subFields;
  161. /**
  162. * 统计列表
  163. */
  164. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  165. /**
  166. * 数字格式
  167. */
  168. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  169. /**
  170. * 实体对象
  171. */
  172. public Class<T> clazz;
  173. /**
  174. * 需要排除列属性
  175. */
  176. public String[] excludeFields;
  177. public ExcelUtil(Class<T> clazz)
  178. {
  179. this.clazz = clazz;
  180. }
  181. /**
  182. * 隐藏Excel中列属性
  183. *
  184. * @param fields 列属性名 示例[单个"name"/多个"id","name"]
  185. * @throws Exception
  186. */
  187. public void hideColumn(String... fields)
  188. {
  189. this.excludeFields = fields;
  190. }
  191. public void init(List<T> list, String sheetName, String title, Type type)
  192. {
  193. if (list == null)
  194. {
  195. list = new ArrayList<T>();
  196. }
  197. this.list = list;
  198. this.sheetName = sheetName;
  199. this.type = type;
  200. this.title = title;
  201. createExcelField();
  202. createWorkbook();
  203. createTitle();
  204. createSubHead();
  205. }
  206. /**
  207. * 创建excel第一行标题
  208. */
  209. public void createTitle()
  210. {
  211. if (StringUtils.isNotEmpty(title))
  212. {
  213. subMergedFirstRowNum++;
  214. subMergedLastRowNum++;
  215. int titleLastCol = this.fields.size() - 1;
  216. if (isSubList())
  217. {
  218. titleLastCol = titleLastCol + subFields.size() - 1;
  219. }
  220. Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
  221. titleRow.setHeightInPoints(30);
  222. Cell titleCell = titleRow.createCell(0);
  223. titleCell.setCellStyle(styles.get("title"));
  224. titleCell.setCellValue(title);
  225. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol));
  226. }
  227. }
  228. /**
  229. * 创建对象的子列表名称
  230. */
  231. public void createSubHead()
  232. {
  233. if (isSubList())
  234. {
  235. subMergedFirstRowNum++;
  236. subMergedLastRowNum++;
  237. Row subRow = sheet.createRow(rownum);
  238. int excelNum = 0;
  239. for (Object[] objects : fields)
  240. {
  241. Excel attr = (Excel) objects[1];
  242. Cell headCell1 = subRow.createCell(excelNum);
  243. headCell1.setCellValue(attr.name());
  244. headCell1.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  245. excelNum++;
  246. }
  247. int headFirstRow = excelNum - 1;
  248. int headLastRow = headFirstRow + subFields.size() - 1;
  249. if (headLastRow > headFirstRow)
  250. {
  251. sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, headFirstRow, headLastRow));
  252. }
  253. rownum++;
  254. }
  255. }
  256. /**
  257. * 对excel表单默认第一个索引名转换成list
  258. *
  259. * @param is 输入流
  260. * @return 转换后集合
  261. */
  262. public List<T> importExcel(InputStream is)
  263. {
  264. List<T> list = null;
  265. try
  266. {
  267. list = importExcel(is, 0);
  268. }
  269. catch (Exception e)
  270. {
  271. log.error("导入Excel异常{}", e.getMessage());
  272. throw new UtilException(e.getMessage());
  273. }
  274. finally
  275. {
  276. IOUtils.closeQuietly(is);
  277. }
  278. return list;
  279. }
  280. /**
  281. * 对excel表单默认第一个索引名转换成list
  282. *
  283. * @param is 输入流
  284. * @param titleNum 标题占用行数
  285. * @return 转换后集合
  286. */
  287. public List<T> importExcel(InputStream is, int titleNum) throws Exception
  288. {
  289. return importExcel(StringUtils.EMPTY, is, titleNum);
  290. }
  291. /**
  292. * 对excel表单指定表格索引名转换成list
  293. *
  294. * @param sheetName 表格索引名
  295. * @param titleNum 标题占用行数
  296. * @param is 输入流
  297. * @return 转换后集合
  298. */
  299. public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
  300. {
  301. this.type = Type.IMPORT;
  302. this.wb = WorkbookFactory.create(is);
  303. List<T> list = new ArrayList<T>();
  304. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
  305. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
  306. if (sheet == null)
  307. {
  308. throw new IOException("文件sheet不存在");
  309. }
  310. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
  311. Map<String, PictureData> pictures;
  312. if (isXSSFWorkbook)
  313. {
  314. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
  315. }
  316. else
  317. {
  318. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
  319. }
  320. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
  321. int rows = sheet.getLastRowNum();
  322. if (rows > 0)
  323. {
  324. // 定义一个map用于存放excel列的序号和field.
  325. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  326. // 获取表头
  327. Row heard = sheet.getRow(titleNum);
  328. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  329. {
  330. Cell cell = heard.getCell(i);
  331. if (StringUtils.isNotNull(cell))
  332. {
  333. String value = this.getCellValue(heard, i).toString();
  334. cellMap.put(value, i);
  335. }
  336. else
  337. {
  338. cellMap.put(null, i);
  339. }
  340. }
  341. // 有数据时才处理 得到类的所有field.
  342. List<Object[]> fields = this.getFields();
  343. Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
  344. for (Object[] objects : fields)
  345. {
  346. Excel attr = (Excel) objects[1];
  347. Integer column = cellMap.get(attr.name());
  348. if (column != null)
  349. {
  350. fieldsMap.put(column, objects);
  351. }
  352. }
  353. for (int i = titleNum + 1; i <= rows; i++)
  354. {
  355. // 从第2行开始取数据,默认第一行是表头.
  356. Row row = sheet.getRow(i);
  357. // 判断当前行是否是空行
  358. if (isRowEmpty(row))
  359. {
  360. continue;
  361. }
  362. T entity = null;
  363. for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
  364. {
  365. Object val = this.getCellValue(row, entry.getKey());
  366. // 如果不存在实例则新建.
  367. entity = (entity == null ? clazz.newInstance() : entity);
  368. // 从map中得到对应列的field.
  369. Field field = (Field) entry.getValue()[0];
  370. Excel attr = (Excel) entry.getValue()[1];
  371. // 取得类型,并根据对象类型设置值.
  372. Class<?> fieldType = field.getType();
  373. if (String.class == fieldType)
  374. {
  375. String s = Convert.toStr(val);
  376. if (StringUtils.endsWith(s, ".0"))
  377. {
  378. val = StringUtils.substringBefore(s, ".0");
  379. }
  380. else
  381. {
  382. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  383. if (StringUtils.isNotEmpty(dateFormat))
  384. {
  385. val = parseDateToStr(dateFormat, val);
  386. }
  387. else
  388. {
  389. val = Convert.toStr(val);
  390. }
  391. }
  392. }
  393. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  394. {
  395. val = Convert.toInt(val);
  396. }
  397. else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  398. {
  399. val = Convert.toLong(val);
  400. }
  401. else if (Double.TYPE == fieldType || Double.class == fieldType)
  402. {
  403. val = Convert.toDouble(val);
  404. }
  405. else if (Float.TYPE == fieldType || Float.class == fieldType)
  406. {
  407. val = Convert.toFloat(val);
  408. }
  409. else if (BigDecimal.class == fieldType)
  410. {
  411. val = Convert.toBigDecimal(val);
  412. }
  413. else if (Date.class == fieldType)
  414. {
  415. if (val instanceof String)
  416. {
  417. val = DateUtils.parseDate(val);
  418. }
  419. else if (val instanceof Double)
  420. {
  421. val = DateUtil.getJavaDate((Double) val);
  422. }
  423. }
  424. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  425. {
  426. val = Convert.toBool(val, false);
  427. }
  428. if (StringUtils.isNotNull(fieldType))
  429. {
  430. String propertyName = field.getName();
  431. if (StringUtils.isNotEmpty(attr.targetAttr()))
  432. {
  433. propertyName = field.getName() + "." + attr.targetAttr();
  434. }
  435. if (StringUtils.isNotEmpty(attr.readConverterExp()))
  436. {
  437. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  438. }
  439. else if (StringUtils.isNotEmpty(attr.dictType()))
  440. {
  441. if (!sysDictMap.containsKey(attr.dictType() + val))
  442. {
  443. String dictValue = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  444. sysDictMap.put(attr.dictType() + val, dictValue);
  445. }
  446. val = sysDictMap.get(attr.dictType() + val);
  447. }
  448. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  449. {
  450. val = dataFormatHandlerAdapter(val, attr, null);
  451. }
  452. else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
  453. {
  454. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
  455. if (image == null)
  456. {
  457. val = "";
  458. }
  459. else
  460. {
  461. byte[] data = image.getData();
  462. val = FileUtils.writeImportBytes(data);
  463. }
  464. }
  465. ReflectUtils.invokeSetter(entity, propertyName, val);
  466. }
  467. }
  468. list.add(entity);
  469. }
  470. }
  471. return list;
  472. }
  473. /**
  474. * 对list数据源将其里面的数据导入到excel表单
  475. *
  476. * @param list 导出数据集合
  477. * @param sheetName 工作表的名称
  478. * @return 结果
  479. */
  480. public AjaxResult exportExcel(List<T> list, String sheetName)
  481. {
  482. return exportExcel(list, sheetName, StringUtils.EMPTY);
  483. }
  484. /**
  485. * 对list数据源将其里面的数据导入到excel表单
  486. *
  487. * @param list 导出数据集合
  488. * @param sheetName 工作表的名称
  489. * @param title 标题
  490. * @return 结果
  491. */
  492. public AjaxResult exportExcel(List<T> list, String sheetName, String title)
  493. {
  494. this.init(list, sheetName, title, Type.EXPORT);
  495. return exportExcel();
  496. }
  497. /**
  498. * 对list数据源将其里面的数据导入到excel表单
  499. *
  500. * @param response 返回数据
  501. * @param list 导出数据集合
  502. * @param sheetName 工作表的名称
  503. * @return 结果
  504. */
  505. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName)
  506. {
  507. exportExcel(response, list, sheetName, StringUtils.EMPTY);
  508. }
  509. /**
  510. * 对list数据源将其里面的数据导入到excel表单
  511. *
  512. * @param response 返回数据
  513. * @param list 导出数据集合
  514. * @param sheetName 工作表的名称
  515. * @param title 标题
  516. * @return 结果
  517. */
  518. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title)
  519. {
  520. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  521. response.setCharacterEncoding("utf-8");
  522. this.init(list, sheetName, title, Type.EXPORT);
  523. exportExcel(response);
  524. }
  525. /**
  526. * 对list数据源将其里面的数据导入到excel表单
  527. *
  528. * @param sheetName 工作表的名称
  529. * @return 结果
  530. */
  531. public AjaxResult importTemplateExcel(String sheetName)
  532. {
  533. return importTemplateExcel(sheetName, StringUtils.EMPTY);
  534. }
  535. /**
  536. * 对list数据源将其里面的数据导入到excel表单
  537. *
  538. * @param sheetName 工作表的名称
  539. * @param title 标题
  540. * @return 结果
  541. */
  542. public AjaxResult importTemplateExcel(String sheetName, String title)
  543. {
  544. this.init(null, sheetName, title, Type.IMPORT);
  545. return exportExcel();
  546. }
  547. /**
  548. * 对list数据源将其里面的数据导入到excel表单
  549. *
  550. * @param sheetName 工作表的名称
  551. * @return 结果
  552. */
  553. public void importTemplateExcel(HttpServletResponse response, String sheetName)
  554. {
  555. importTemplateExcel(response, sheetName, StringUtils.EMPTY);
  556. }
  557. /**
  558. * 对list数据源将其里面的数据导入到excel表单
  559. *
  560. * @param sheetName 工作表的名称
  561. * @param title 标题
  562. * @return 结果
  563. */
  564. public void importTemplateExcel(HttpServletResponse response, String sheetName, String title)
  565. {
  566. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  567. response.setCharacterEncoding("utf-8");
  568. this.init(null, sheetName, title, Type.IMPORT);
  569. exportExcel(response);
  570. }
  571. /**
  572. * 对list数据源将其里面的数据导入到excel表单
  573. *
  574. * @return 结果
  575. */
  576. public void exportExcel(HttpServletResponse response)
  577. {
  578. try
  579. {
  580. writeSheet();
  581. wb.write(response.getOutputStream());
  582. }
  583. catch (Exception e)
  584. {
  585. log.error("导出Excel异常{}", e.getMessage());
  586. }
  587. finally
  588. {
  589. IOUtils.closeQuietly(wb);
  590. }
  591. }
  592. /**
  593. * 对list数据源将其里面的数据导入到excel表单
  594. *
  595. * @return 结果
  596. */
  597. public AjaxResult exportExcel()
  598. {
  599. OutputStream out = null;
  600. try
  601. {
  602. writeSheet();
  603. String filename = encodingFilename(sheetName);
  604. out = new FileOutputStream(getAbsoluteFile(filename));
  605. wb.write(out);
  606. return AjaxResult.success(filename);
  607. }
  608. catch (Exception e)
  609. {
  610. log.error("导出Excel异常{}", e.getMessage());
  611. throw new UtilException("导出Excel失败,请联系网站管理员!");
  612. }
  613. finally
  614. {
  615. IOUtils.closeQuietly(wb);
  616. IOUtils.closeQuietly(out);
  617. }
  618. }
  619. /**
  620. * 创建写入数据到Sheet
  621. */
  622. public void writeSheet()
  623. {
  624. // 取出一共有多少个sheet.
  625. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
  626. for (int index = 0; index < sheetNo; index++)
  627. {
  628. createSheet(sheetNo, index);
  629. // 产生一行
  630. Row row = sheet.createRow(rownum);
  631. int column = 0;
  632. // 写入各个字段的列头名称
  633. for (Object[] os : fields)
  634. {
  635. Field field = (Field) os[0];
  636. Excel excel = (Excel) os[1];
  637. if (Collection.class.isAssignableFrom(field.getType()))
  638. {
  639. for (Field subField : subFields)
  640. {
  641. Excel subExcel = subField.getAnnotation(Excel.class);
  642. this.createHeadCell(subExcel, row, column++);
  643. }
  644. }
  645. else
  646. {
  647. this.createHeadCell(excel, row, column++);
  648. }
  649. }
  650. if (Type.EXPORT.equals(type))
  651. {
  652. fillExcelData(index, row);
  653. addStatisticsRow();
  654. }
  655. }
  656. }
  657. /**
  658. * 填充excel数据
  659. *
  660. * @param index 序号
  661. * @param row 单元格行
  662. */
  663. @SuppressWarnings("unchecked")
  664. public void fillExcelData(int index, Row row)
  665. {
  666. int startNo = index * sheetSize;
  667. int endNo = Math.min(startNo + sheetSize, list.size());
  668. int rowNo = (1 + rownum) - startNo;
  669. for (int i = startNo; i < endNo; i++)
  670. {
  671. rowNo = isSubList() ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rownum - startNo;
  672. row = sheet.createRow(rowNo);
  673. // 得到导出对象.
  674. T vo = (T) list.get(i);
  675. Collection<?> subList = null;
  676. if (isSubList())
  677. {
  678. if (isSubListValue(vo))
  679. {
  680. subList = getListCellValue(vo);
  681. subMergedLastRowNum = subMergedLastRowNum + subList.size();
  682. }
  683. else
  684. {
  685. subMergedFirstRowNum++;
  686. subMergedLastRowNum++;
  687. }
  688. }
  689. int column = 0;
  690. for (Object[] os : fields)
  691. {
  692. Field field = (Field) os[0];
  693. Excel excel = (Excel) os[1];
  694. if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList))
  695. {
  696. boolean subFirst = false;
  697. for (Object obj : subList)
  698. {
  699. if (subFirst)
  700. {
  701. rowNo++;
  702. row = sheet.createRow(rowNo);
  703. }
  704. List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
  705. int subIndex = 0;
  706. for (Field subField : subFields)
  707. {
  708. if (subField.isAnnotationPresent(Excel.class))
  709. {
  710. subField.setAccessible(true);
  711. Excel attr = subField.getAnnotation(Excel.class);
  712. this.addCell(attr, row, (T) obj, subField, column + subIndex);
  713. }
  714. subIndex++;
  715. }
  716. subFirst = true;
  717. }
  718. this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
  719. }
  720. else
  721. {
  722. this.addCell(excel, row, vo, field, column++);
  723. }
  724. }
  725. }
  726. }
  727. /**
  728. * 创建表格样式
  729. *
  730. * @param wb 工作薄对象
  731. * @return 样式列表
  732. */
  733. private Map<String, CellStyle> createStyles(Workbook wb)
  734. {
  735. // 写入各条记录,每条记录对应excel表中的一行
  736. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  737. CellStyle style = wb.createCellStyle();
  738. style.setAlignment(HorizontalAlignment.CENTER);
  739. style.setVerticalAlignment(VerticalAlignment.CENTER);
  740. Font titleFont = wb.createFont();
  741. titleFont.setFontName("Arial");
  742. titleFont.setFontHeightInPoints((short) 16);
  743. titleFont.setBold(true);
  744. style.setFont(titleFont);
  745. DataFormat dataFormat = wb.createDataFormat();
  746. style.setDataFormat(dataFormat.getFormat("@"));
  747. styles.put("title", style);
  748. style = wb.createCellStyle();
  749. style.setAlignment(HorizontalAlignment.CENTER);
  750. style.setVerticalAlignment(VerticalAlignment.CENTER);
  751. style.setBorderRight(BorderStyle.THIN);
  752. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  753. style.setBorderLeft(BorderStyle.THIN);
  754. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  755. style.setBorderTop(BorderStyle.THIN);
  756. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  757. style.setBorderBottom(BorderStyle.THIN);
  758. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  759. Font dataFont = wb.createFont();
  760. dataFont.setFontName("Arial");
  761. dataFont.setFontHeightInPoints((short) 10);
  762. style.setFont(dataFont);
  763. styles.put("data", style);
  764. style = wb.createCellStyle();
  765. style.setAlignment(HorizontalAlignment.CENTER);
  766. style.setVerticalAlignment(VerticalAlignment.CENTER);
  767. Font totalFont = wb.createFont();
  768. totalFont.setFontName("Arial");
  769. totalFont.setFontHeightInPoints((short) 10);
  770. style.setFont(totalFont);
  771. styles.put("total", style);
  772. styles.putAll(annotationHeaderStyles(wb, styles));
  773. styles.putAll(annotationDataStyles(wb));
  774. return styles;
  775. }
  776. /**
  777. * 根据Excel注解创建表格头样式
  778. *
  779. * @param wb 工作薄对象
  780. * @return 自定义样式列表
  781. */
  782. private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles)
  783. {
  784. Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>();
  785. for (Object[] os : fields)
  786. {
  787. Excel excel = (Excel) os[1];
  788. String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor());
  789. if (!headerStyles.containsKey(key))
  790. {
  791. CellStyle style = wb.createCellStyle();
  792. style.cloneStyleFrom(styles.get("data"));
  793. style.setAlignment(HorizontalAlignment.CENTER);
  794. style.setVerticalAlignment(VerticalAlignment.CENTER);
  795. style.setFillForegroundColor(excel.headerBackgroundColor().index);
  796. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  797. Font headerFont = wb.createFont();
  798. headerFont.setFontName("Arial");
  799. headerFont.setFontHeightInPoints((short) 10);
  800. headerFont.setBold(true);
  801. headerFont.setColor(excel.headerColor().index);
  802. style.setFont(headerFont);
  803. // 设置表格头单元格文本形式
  804. DataFormat dataFormat = wb.createDataFormat();
  805. style.setDataFormat(dataFormat.getFormat("@"));
  806. headerStyles.put(key, style);
  807. }
  808. }
  809. return headerStyles;
  810. }
  811. /**
  812. * 根据Excel注解创建表格列样式
  813. *
  814. * @param wb 工作薄对象
  815. * @return 自定义样式列表
  816. */
  817. private Map<String, CellStyle> annotationDataStyles(Workbook wb)
  818. {
  819. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  820. for (Object[] os : fields)
  821. {
  822. Field field = (Field) os[0];
  823. Excel excel = (Excel) os[1];
  824. if (Collection.class.isAssignableFrom(field.getType()))
  825. {
  826. ParameterizedType pt = (ParameterizedType) field.getGenericType();
  827. Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
  828. List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
  829. for (Field subField : subFields)
  830. {
  831. Excel subExcel = subField.getAnnotation(Excel.class);
  832. annotationDataStyles(styles, subField, subExcel);
  833. }
  834. }
  835. else
  836. {
  837. annotationDataStyles(styles, field, excel);
  838. }
  839. }
  840. return styles;
  841. }
  842. /**
  843. * 根据Excel注解创建表格列样式
  844. *
  845. * @param styles 自定义样式列表
  846. * @param field 属性列信息
  847. * @param excel 注解信息
  848. */
  849. public void annotationDataStyles(Map<String, CellStyle> styles, Field field, Excel excel)
  850. {
  851. String key = StringUtils.format("data_{}_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor(), excel.cellType());
  852. if (!styles.containsKey(key))
  853. {
  854. CellStyle style = wb.createCellStyle();
  855. style.setAlignment(excel.align());
  856. style.setVerticalAlignment(VerticalAlignment.CENTER);
  857. style.setBorderRight(BorderStyle.THIN);
  858. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  859. style.setBorderLeft(BorderStyle.THIN);
  860. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  861. style.setBorderTop(BorderStyle.THIN);
  862. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  863. style.setBorderBottom(BorderStyle.THIN);
  864. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  865. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  866. style.setFillForegroundColor(excel.backgroundColor().getIndex());
  867. Font dataFont = wb.createFont();
  868. dataFont.setFontName("Arial");
  869. dataFont.setFontHeightInPoints((short) 10);
  870. dataFont.setColor(excel.color().index);
  871. style.setFont(dataFont);
  872. if (ColumnType.TEXT == excel.cellType())
  873. {
  874. DataFormat dataFormat = wb.createDataFormat();
  875. style.setDataFormat(dataFormat.getFormat("@"));
  876. }
  877. styles.put(key, style);
  878. }
  879. }
  880. /**
  881. * 创建单元格
  882. */
  883. public Cell createHeadCell(Excel attr, Row row, int column)
  884. {
  885. // 创建列
  886. Cell cell = row.createCell(column);
  887. // 写入列信息
  888. cell.setCellValue(attr.name());
  889. setDataValidation(attr, row, column);
  890. cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  891. if (isSubList())
  892. {
  893. // 填充默认样式,防止合并单元格样式失效
  894. sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType())));
  895. if (attr.needMerge())
  896. {
  897. sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column));
  898. }
  899. }
  900. return cell;
  901. }
  902. /**
  903. * 设置单元格信息
  904. *
  905. * @param value 单元格值
  906. * @param attr 注解相关
  907. * @param cell 单元格信息
  908. */
  909. public void setCellVo(Object value, Excel attr, Cell cell)
  910. {
  911. if (ColumnType.STRING == attr.cellType() || ColumnType.TEXT == attr.cellType())
  912. {
  913. String cellValue = Convert.toStr(value);
  914. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  915. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  916. {
  917. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  918. }
  919. if (value instanceof Collection && StringUtils.equals("[]", cellValue))
  920. {
  921. cellValue = StringUtils.EMPTY;
  922. }
  923. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  924. }
  925. else if (ColumnType.NUMERIC == attr.cellType())
  926. {
  927. if (StringUtils.isNotNull(value))
  928. {
  929. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  930. }
  931. }
  932. else if (ColumnType.IMAGE == attr.cellType())
  933. {
  934. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  935. String imagePath = Convert.toStr(value);
  936. if (StringUtils.isNotEmpty(imagePath))
  937. {
  938. byte[] data = ImageUtils.getImage(imagePath);
  939. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  940. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  941. }
  942. }
  943. }
  944. /**
  945. * 获取画布
  946. */
  947. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  948. {
  949. if (sheet.getDrawingPatriarch() == null)
  950. {
  951. sheet.createDrawingPatriarch();
  952. }
  953. return sheet.getDrawingPatriarch();
  954. }
  955. /**
  956. * 获取图片类型,设置图片插入类型
  957. */
  958. public int getImageType(byte[] value)
  959. {
  960. String type = FileTypeUtils.getFileExtendName(value);
  961. if ("JPG".equalsIgnoreCase(type))
  962. {
  963. return Workbook.PICTURE_TYPE_JPEG;
  964. }
  965. else if ("PNG".equalsIgnoreCase(type))
  966. {
  967. return Workbook.PICTURE_TYPE_PNG;
  968. }
  969. return Workbook.PICTURE_TYPE_JPEG;
  970. }
  971. /**
  972. * 创建表格样式
  973. */
  974. public void setDataValidation(Excel attr, Row row, int column)
  975. {
  976. if (attr.name().indexOf("注:") >= 0)
  977. {
  978. sheet.setColumnWidth(column, 6000);
  979. }
  980. else
  981. {
  982. // 设置列宽
  983. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  984. }
  985. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  986. {
  987. if (attr.combo().length > 15 || StringUtils.join(attr.combo()).length() > 255)
  988. {
  989. // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到
  990. setXSSFValidationWithHidden(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  991. }
  992. else
  993. {
  994. // 提示信息或只能选择不能输入的列内容.
  995. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  996. }
  997. }
  998. }
  999. /**
  1000. * 添加单元格
  1001. */
  1002. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  1003. {
  1004. Cell cell = null;
  1005. try
  1006. {
  1007. // 设置行高
  1008. row.setHeight(maxHeight);
  1009. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  1010. if (attr.isExport())
  1011. {
  1012. // 创建cell
  1013. cell = row.createCell(column);
  1014. if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge())
  1015. {
  1016. CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
  1017. sheet.addMergedRegion(cellAddress);
  1018. }
  1019. cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType())));
  1020. // 用于读取对象中的属性
  1021. Object value = getTargetValue(vo, field, attr);
  1022. String dateFormat = attr.dateFormat();
  1023. String readConverterExp = attr.readConverterExp();
  1024. String separator = attr.separator();
  1025. String dictType = attr.dictType();
  1026. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  1027. {
  1028. cell.setCellValue(parseDateToStr(dateFormat, value));
  1029. }
  1030. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  1031. {
  1032. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  1033. }
  1034. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  1035. {
  1036. if (!sysDictMap.containsKey(dictType + value))
  1037. {
  1038. String lable = convertDictByExp(Convert.toStr(value), dictType, separator);
  1039. sysDictMap.put(dictType + value, lable);
  1040. }
  1041. cell.setCellValue(sysDictMap.get(dictType + value));
  1042. }
  1043. else if (value instanceof BigDecimal && -1 != attr.scale())
  1044. {
  1045. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue());
  1046. }
  1047. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  1048. {
  1049. cell.setCellValue(dataFormatHandlerAdapter(value, attr, cell));
  1050. }
  1051. else
  1052. {
  1053. // 设置列类型
  1054. setCellVo(value, attr, cell);
  1055. }
  1056. addStatisticsData(column, Convert.toStr(value), attr);
  1057. }
  1058. }
  1059. catch (Exception e)
  1060. {
  1061. log.error("导出Excel失败{}", e);
  1062. }
  1063. return cell;
  1064. }
  1065. /**
  1066. * 设置 POI XSSFSheet 单元格提示或选择框
  1067. *
  1068. * @param sheet 表单
  1069. * @param textlist 下拉框显示的内容
  1070. * @param promptContent 提示内容
  1071. * @param firstRow 开始行
  1072. * @param endRow 结束行
  1073. * @param firstCol 开始列
  1074. * @param endCol 结束列
  1075. */
  1076. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  1077. int firstCol, int endCol)
  1078. {
  1079. DataValidationHelper helper = sheet.getDataValidationHelper();
  1080. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  1081. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1082. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1083. if (StringUtils.isNotEmpty(promptContent))
  1084. {
  1085. // 如果设置了提示信息则鼠标放上去提示
  1086. dataValidation.createPromptBox("", promptContent);
  1087. dataValidation.setShowPromptBox(true);
  1088. }
  1089. // 处理Excel兼容性问题
  1090. if (dataValidation instanceof XSSFDataValidation)
  1091. {
  1092. dataValidation.setSuppressDropDownArrow(true);
  1093. dataValidation.setShowErrorBox(true);
  1094. }
  1095. else
  1096. {
  1097. dataValidation.setSuppressDropDownArrow(false);
  1098. }
  1099. sheet.addValidationData(dataValidation);
  1100. }
  1101. /**
  1102. * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框).
  1103. *
  1104. * @param sheet 要设置的sheet.
  1105. * @param textlist 下拉框显示的内容
  1106. * @param promptContent 提示内容
  1107. * @param firstRow 开始行
  1108. * @param endRow 结束行
  1109. * @param firstCol 开始列
  1110. * @param endCol 结束列
  1111. */
  1112. public void setXSSFValidationWithHidden(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol)
  1113. {
  1114. String hideSheetName = "combo_" + firstCol + "_" + endCol;
  1115. Sheet hideSheet = wb.createSheet(hideSheetName); // 用于存储 下拉菜单数据
  1116. for (int i = 0; i < textlist.length; i++)
  1117. {
  1118. hideSheet.createRow(i).createCell(0).setCellValue(textlist[i]);
  1119. }
  1120. // 创建名称,可被其他单元格引用
  1121. Name name = wb.createName();
  1122. name.setNameName(hideSheetName + "_data");
  1123. name.setRefersToFormula(hideSheetName + "!$A$1:$A$" + textlist.length);
  1124. DataValidationHelper helper = sheet.getDataValidationHelper();
  1125. // 加载下拉列表内容
  1126. DataValidationConstraint constraint = helper.createFormulaListConstraint(hideSheetName + "_data");
  1127. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  1128. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1129. // 数据有效性对象
  1130. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1131. if (StringUtils.isNotEmpty(promptContent))
  1132. {
  1133. // 如果设置了提示信息则鼠标放上去提示
  1134. dataValidation.createPromptBox("", promptContent);
  1135. dataValidation.setShowPromptBox(true);
  1136. }
  1137. // 处理Excel兼容性问题
  1138. if (dataValidation instanceof XSSFDataValidation)
  1139. {
  1140. dataValidation.setSuppressDropDownArrow(true);
  1141. dataValidation.setShowErrorBox(true);
  1142. }
  1143. else
  1144. {
  1145. dataValidation.setSuppressDropDownArrow(false);
  1146. }
  1147. sheet.addValidationData(dataValidation);
  1148. // 设置hiddenSheet隐藏
  1149. wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
  1150. }
  1151. /**
  1152. * 解析导出值 0=男,1=女,2=未知
  1153. *
  1154. * @param propertyValue 参数值
  1155. * @param converterExp 翻译注解
  1156. * @param separator 分隔符
  1157. * @return 解析后值
  1158. */
  1159. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1160. {
  1161. StringBuilder propertyString = new StringBuilder();
  1162. String[] convertSource = converterExp.split(",");
  1163. for (String item : convertSource)
  1164. {
  1165. String[] itemArray = item.split("=");
  1166. if (StringUtils.containsAny(propertyValue, separator))
  1167. {
  1168. for (String value : propertyValue.split(separator))
  1169. {
  1170. if (itemArray[0].equals(value))
  1171. {
  1172. propertyString.append(itemArray[1] + separator);
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. else
  1178. {
  1179. if (itemArray[0].equals(propertyValue))
  1180. {
  1181. return itemArray[1];
  1182. }
  1183. }
  1184. }
  1185. return StringUtils.stripEnd(propertyString.toString(), separator);
  1186. }
  1187. /**
  1188. * 反向解析值 男=0,女=1,未知=2
  1189. *
  1190. * @param propertyValue 参数值
  1191. * @param converterExp 翻译注解
  1192. * @param separator 分隔符
  1193. * @return 解析后值
  1194. */
  1195. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1196. {
  1197. StringBuilder propertyString = new StringBuilder();
  1198. String[] convertSource = converterExp.split(",");
  1199. for (String item : convertSource)
  1200. {
  1201. String[] itemArray = item.split("=");
  1202. if (StringUtils.containsAny(propertyValue, separator))
  1203. {
  1204. for (String value : propertyValue.split(separator))
  1205. {
  1206. if (itemArray[1].equals(value))
  1207. {
  1208. propertyString.append(itemArray[0] + separator);
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. else
  1214. {
  1215. if (itemArray[1].equals(propertyValue))
  1216. {
  1217. return itemArray[0];
  1218. }
  1219. }
  1220. }
  1221. return StringUtils.stripEnd(propertyString.toString(), separator);
  1222. }
  1223. /**
  1224. * 解析字典值
  1225. *
  1226. * @param dictValue 字典值
  1227. * @param dictType 字典类型
  1228. * @param separator 分隔符
  1229. * @return 字典标签
  1230. */
  1231. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1232. {
  1233. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1234. }
  1235. /**
  1236. * 反向解析值字典值
  1237. *
  1238. * @param dictLabel 字典标签
  1239. * @param dictType 字典类型
  1240. * @param separator 分隔符
  1241. * @return 字典值
  1242. */
  1243. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1244. {
  1245. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1246. }
  1247. /**
  1248. * 数据处理器
  1249. *
  1250. * @param value 数据值
  1251. * @param excel 数据注解
  1252. * @return
  1253. */
  1254. public String dataFormatHandlerAdapter(Object value, Excel excel, Cell cell)
  1255. {
  1256. try
  1257. {
  1258. Object instance = excel.handler().newInstance();
  1259. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class });
  1260. value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb);
  1261. }
  1262. catch (Exception e)
  1263. {
  1264. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1265. }
  1266. return Convert.toStr(value);
  1267. }
  1268. /**
  1269. * 合计统计信息
  1270. */
  1271. private void addStatisticsData(Integer index, String text, Excel entity)
  1272. {
  1273. if (entity != null && entity.isStatistics())
  1274. {
  1275. Double temp = 0D;
  1276. if (!statistics.containsKey(index))
  1277. {
  1278. statistics.put(index, temp);
  1279. }
  1280. try
  1281. {
  1282. temp = Double.valueOf(text);
  1283. }
  1284. catch (NumberFormatException e)
  1285. {
  1286. }
  1287. statistics.put(index, statistics.get(index) + temp);
  1288. }
  1289. }
  1290. /**
  1291. * 创建统计行
  1292. */
  1293. public void addStatisticsRow()
  1294. {
  1295. if (statistics.size() > 0)
  1296. {
  1297. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1298. Set<Integer> keys = statistics.keySet();
  1299. Cell cell = row.createCell(0);
  1300. cell.setCellStyle(styles.get("total"));
  1301. cell.setCellValue("合计");
  1302. for (Integer key : keys)
  1303. {
  1304. cell = row.createCell(key);
  1305. cell.setCellStyle(styles.get("total"));
  1306. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1307. }
  1308. statistics.clear();
  1309. }
  1310. }
  1311. /**
  1312. * 编码文件名
  1313. */
  1314. public String encodingFilename(String filename)
  1315. {
  1316. filename = UUID.randomUUID() + "_" + filename + ".xlsx";
  1317. return filename;
  1318. }
  1319. /**
  1320. * 获取下载路径
  1321. *
  1322. * @param filename 文件名称
  1323. */
  1324. public String getAbsoluteFile(String filename)
  1325. {
  1326. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1327. File desc = new File(downloadPath);
  1328. if (!desc.getParentFile().exists())
  1329. {
  1330. desc.getParentFile().mkdirs();
  1331. }
  1332. return downloadPath;
  1333. }
  1334. /**
  1335. * 获取bean中的属性值
  1336. *
  1337. * @param vo 实体对象
  1338. * @param field 字段
  1339. * @param excel 注解
  1340. * @return 最终的属性值
  1341. * @throws Exception
  1342. */
  1343. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1344. {
  1345. Object o = field.get(vo);
  1346. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1347. {
  1348. String target = excel.targetAttr();
  1349. if (target.contains("."))
  1350. {
  1351. String[] targets = target.split("[.]");
  1352. for (String name : targets)
  1353. {
  1354. o = getValue(o, name);
  1355. }
  1356. }
  1357. else
  1358. {
  1359. o = getValue(o, target);
  1360. }
  1361. }
  1362. return o;
  1363. }
  1364. /**
  1365. * 以类的属性的get方法方法形式获取值
  1366. *
  1367. * @param o
  1368. * @param name
  1369. * @return value
  1370. * @throws Exception
  1371. */
  1372. private Object getValue(Object o, String name) throws Exception
  1373. {
  1374. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1375. {
  1376. Class<?> clazz = o.getClass();
  1377. Field field = clazz.getDeclaredField(name);
  1378. field.setAccessible(true);
  1379. o = field.get(o);
  1380. }
  1381. return o;
  1382. }
  1383. /**
  1384. * 得到所有定义字段
  1385. */
  1386. private void createExcelField()
  1387. {
  1388. this.fields = getFields();
  1389. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1390. this.maxHeight = getRowHeight();
  1391. }
  1392. /**
  1393. * 获取字段注解信息
  1394. */
  1395. public List<Object[]> getFields()
  1396. {
  1397. List<Object[]> fields = new ArrayList<Object[]>();
  1398. List<Field> tempFields = new ArrayList<>();
  1399. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1400. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1401. for (Field field : tempFields)
  1402. {
  1403. if (!ArrayUtils.contains(this.excludeFields, field.getName()))
  1404. {
  1405. // 单注解
  1406. if (field.isAnnotationPresent(Excel.class))
  1407. {
  1408. Excel attr = field.getAnnotation(Excel.class);
  1409. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1410. {
  1411. field.setAccessible(true);
  1412. fields.add(new Object[] { field, attr });
  1413. }
  1414. if (Collection.class.isAssignableFrom(field.getType()))
  1415. {
  1416. subMethod = getSubMethod(field.getName(), clazz);
  1417. ParameterizedType pt = (ParameterizedType) field.getGenericType();
  1418. Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
  1419. this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
  1420. }
  1421. }
  1422. // 多注解
  1423. if (field.isAnnotationPresent(Excels.class))
  1424. {
  1425. Excels attrs = field.getAnnotation(Excels.class);
  1426. Excel[] excels = attrs.value();
  1427. for (Excel attr : excels)
  1428. {
  1429. if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr())
  1430. && (attr != null && (attr.type() == Type.ALL || attr.type() == type)))
  1431. {
  1432. field.setAccessible(true);
  1433. fields.add(new Object[] { field, attr });
  1434. }
  1435. }
  1436. }
  1437. }
  1438. }
  1439. return fields;
  1440. }
  1441. /**
  1442. * 根据注解获取最大行高
  1443. */
  1444. public short getRowHeight()
  1445. {
  1446. double maxHeight = 0;
  1447. for (Object[] os : this.fields)
  1448. {
  1449. Excel excel = (Excel) os[1];
  1450. maxHeight = Math.max(maxHeight, excel.height());
  1451. }
  1452. return (short) (maxHeight * 20);
  1453. }
  1454. /**
  1455. * 创建一个工作簿
  1456. */
  1457. public void createWorkbook()
  1458. {
  1459. this.wb = new SXSSFWorkbook(500);
  1460. this.sheet = wb.createSheet();
  1461. wb.setSheetName(0, sheetName);
  1462. this.styles = createStyles(wb);
  1463. }
  1464. /**
  1465. * 创建工作表
  1466. *
  1467. * @param sheetNo sheet数量
  1468. * @param index 序号
  1469. */
  1470. public void createSheet(int sheetNo, int index)
  1471. {
  1472. // 设置工作表的名称.
  1473. if (sheetNo > 1 && index > 0)
  1474. {
  1475. this.sheet = wb.createSheet();
  1476. this.createTitle();
  1477. wb.setSheetName(index, sheetName + index);
  1478. }
  1479. }
  1480. /**
  1481. * 获取单元格值
  1482. *
  1483. * @param row 获取的行
  1484. * @param column 获取单元格列号
  1485. * @return 单元格值
  1486. */
  1487. public Object getCellValue(Row row, int column)
  1488. {
  1489. if (row == null)
  1490. {
  1491. return row;
  1492. }
  1493. Object val = "";
  1494. try
  1495. {
  1496. Cell cell = row.getCell(column);
  1497. if (StringUtils.isNotNull(cell))
  1498. {
  1499. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1500. {
  1501. val = cell.getNumericCellValue();
  1502. if (DateUtil.isCellDateFormatted(cell))
  1503. {
  1504. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1505. }
  1506. else
  1507. {
  1508. if ((Double) val % 1 != 0)
  1509. {
  1510. val = new BigDecimal(val.toString());
  1511. }
  1512. else
  1513. {
  1514. val = new DecimalFormat("0").format(val);
  1515. }
  1516. }
  1517. }
  1518. else if (cell.getCellType() == CellType.STRING)
  1519. {
  1520. val = cell.getStringCellValue();
  1521. }
  1522. else if (cell.getCellType() == CellType.BOOLEAN)
  1523. {
  1524. val = cell.getBooleanCellValue();
  1525. }
  1526. else if (cell.getCellType() == CellType.ERROR)
  1527. {
  1528. val = cell.getErrorCellValue();
  1529. }
  1530. }
  1531. }
  1532. catch (Exception e)
  1533. {
  1534. return val;
  1535. }
  1536. return val;
  1537. }
  1538. /**
  1539. * 判断是否是空行
  1540. *
  1541. * @param row 判断的行
  1542. * @return
  1543. */
  1544. private boolean isRowEmpty(Row row)
  1545. {
  1546. if (row == null)
  1547. {
  1548. return true;
  1549. }
  1550. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1551. {
  1552. Cell cell = row.getCell(i);
  1553. if (cell != null && cell.getCellType() != CellType.BLANK)
  1554. {
  1555. return false;
  1556. }
  1557. }
  1558. return true;
  1559. }
  1560. /**
  1561. * 获取Excel2003图片
  1562. *
  1563. * @param sheet 当前sheet对象
  1564. * @param workbook 工作簿对象
  1565. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1566. */
  1567. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1568. {
  1569. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1570. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1571. if (!pictures.isEmpty())
  1572. {
  1573. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1574. {
  1575. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1576. if (shape instanceof HSSFPicture)
  1577. {
  1578. HSSFPicture pic = (HSSFPicture) shape;
  1579. int pictureIndex = pic.getPictureIndex() - 1;
  1580. HSSFPictureData picData = pictures.get(pictureIndex);
  1581. String picIndex = anchor.getRow1() + "_" + anchor.getCol1();
  1582. sheetIndexPicMap.put(picIndex, picData);
  1583. }
  1584. }
  1585. return sheetIndexPicMap;
  1586. }
  1587. else
  1588. {
  1589. return sheetIndexPicMap;
  1590. }
  1591. }
  1592. /**
  1593. * 获取Excel2007图片
  1594. *
  1595. * @param sheet 当前sheet对象
  1596. * @param workbook 工作簿对象
  1597. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1598. */
  1599. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1600. {
  1601. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1602. for (POIXMLDocumentPart dr : sheet.getRelations())
  1603. {
  1604. if (dr instanceof XSSFDrawing)
  1605. {
  1606. XSSFDrawing drawing = (XSSFDrawing) dr;
  1607. List<XSSFShape> shapes = drawing.getShapes();
  1608. for (XSSFShape shape : shapes)
  1609. {
  1610. if (shape instanceof XSSFPicture)
  1611. {
  1612. XSSFPicture pic = (XSSFPicture) shape;
  1613. XSSFClientAnchor anchor = pic.getPreferredSize();
  1614. CTMarker ctMarker = anchor.getFrom();
  1615. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1616. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1617. }
  1618. }
  1619. }
  1620. }
  1621. return sheetIndexPicMap;
  1622. }
  1623. /**
  1624. * 格式化不同类型的日期对象
  1625. *
  1626. * @param dateFormat 日期格式
  1627. * @param val 被格式化的日期对象
  1628. * @return 格式化后的日期字符
  1629. */
  1630. public String parseDateToStr(String dateFormat, Object val)
  1631. {
  1632. if (val == null)
  1633. {
  1634. return "";
  1635. }
  1636. String str;
  1637. if (val instanceof Date)
  1638. {
  1639. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1640. }
  1641. else if (val instanceof LocalDateTime)
  1642. {
  1643. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1644. }
  1645. else if (val instanceof LocalDate)
  1646. {
  1647. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1648. }
  1649. else
  1650. {
  1651. str = val.toString();
  1652. }
  1653. return str;
  1654. }
  1655. /**
  1656. * 是否有对象的子列表
  1657. */
  1658. public boolean isSubList()
  1659. {
  1660. return StringUtils.isNotNull(subFields) && subFields.size() > 0;
  1661. }
  1662. /**
  1663. * 是否有对象的子列表,集合不为空
  1664. */
  1665. public boolean isSubListValue(T vo)
  1666. {
  1667. return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0;
  1668. }
  1669. /**
  1670. * 获取集合的值
  1671. */
  1672. public Collection<?> getListCellValue(Object obj)
  1673. {
  1674. Object value;
  1675. try
  1676. {
  1677. value = subMethod.invoke(obj, new Object[] {});
  1678. }
  1679. catch (Exception e)
  1680. {
  1681. return new ArrayList<Object>();
  1682. }
  1683. return (Collection<?>) value;
  1684. }
  1685. /**
  1686. * 获取对象的子列表方法
  1687. *
  1688. * @param name 名称
  1689. * @param pojoClass 类对象
  1690. * @return 子列表方法
  1691. */
  1692. public Method getSubMethod(String name, Class<?> pojoClass)
  1693. {
  1694. StringBuffer getMethodName = new StringBuffer("get");
  1695. getMethodName.append(name.substring(0, 1).toUpperCase());
  1696. getMethodName.append(name.substring(1));
  1697. Method method = null;
  1698. try
  1699. {
  1700. method = pojoClass.getMethod(getMethodName.toString(), new Class[] {});
  1701. }
  1702. catch (Exception e)
  1703. {
  1704. log.error("获取对象异常{}", e.getMessage());
  1705. }
  1706. return method;
  1707. }
  1708. }