ExcelUtil.java 59 KB

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