ExcelUtil.java 65 KB

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