ExcelUtil.java 56 KB

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