ExcelUtil.java 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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 = i > 1 ? rowNo + 1 : rowNo + i;
  647. row = sheet.createRow(rowNo);
  648. // 得到导出对象.
  649. T vo = (T) list.get(i);
  650. Collection<?> subList = null;
  651. if (isSubListValue(vo))
  652. {
  653. subList = getListCellValue(vo);
  654. subMergedLastRowNum = subMergedLastRowNum + subList.size();
  655. }
  656. int column = 0;
  657. for (Object[] os : fields)
  658. {
  659. Field field = (Field) os[0];
  660. Excel excel = (Excel) os[1];
  661. if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList))
  662. {
  663. boolean subFirst = false;
  664. for (Object obj : subList)
  665. {
  666. if (subFirst)
  667. {
  668. rowNo++;
  669. row = sheet.createRow(rowNo);
  670. }
  671. List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
  672. int subIndex = 0;
  673. for (Field subField : subFields)
  674. {
  675. if (subField.isAnnotationPresent(Excel.class))
  676. {
  677. subField.setAccessible(true);
  678. Excel attr = subField.getAnnotation(Excel.class);
  679. this.addCell(attr, row, (T) obj, subField, column + subIndex);
  680. }
  681. subIndex++;
  682. }
  683. subFirst = true;
  684. }
  685. this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
  686. }
  687. else
  688. {
  689. this.addCell(excel, row, vo, field, column++);
  690. }
  691. }
  692. }
  693. }
  694. /**
  695. * 创建表格样式
  696. *
  697. * @param wb 工作薄对象
  698. * @return 样式列表
  699. */
  700. private Map<String, CellStyle> createStyles(Workbook wb)
  701. {
  702. // 写入各条记录,每条记录对应excel表中的一行
  703. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  704. CellStyle style = wb.createCellStyle();
  705. style.setAlignment(HorizontalAlignment.CENTER);
  706. style.setVerticalAlignment(VerticalAlignment.CENTER);
  707. Font titleFont = wb.createFont();
  708. titleFont.setFontName("Arial");
  709. titleFont.setFontHeightInPoints((short) 16);
  710. titleFont.setBold(true);
  711. style.setFont(titleFont);
  712. styles.put("title", style);
  713. style = wb.createCellStyle();
  714. style.setAlignment(HorizontalAlignment.CENTER);
  715. style.setVerticalAlignment(VerticalAlignment.CENTER);
  716. style.setBorderRight(BorderStyle.THIN);
  717. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  718. style.setBorderLeft(BorderStyle.THIN);
  719. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  720. style.setBorderTop(BorderStyle.THIN);
  721. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  722. style.setBorderBottom(BorderStyle.THIN);
  723. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  724. Font dataFont = wb.createFont();
  725. dataFont.setFontName("Arial");
  726. dataFont.setFontHeightInPoints((short) 10);
  727. style.setFont(dataFont);
  728. styles.put("data", style);
  729. style = wb.createCellStyle();
  730. style.setAlignment(HorizontalAlignment.CENTER);
  731. style.setVerticalAlignment(VerticalAlignment.CENTER);
  732. Font totalFont = wb.createFont();
  733. totalFont.setFontName("Arial");
  734. totalFont.setFontHeightInPoints((short) 10);
  735. style.setFont(totalFont);
  736. styles.put("total", style);
  737. styles.putAll(annotationHeaderStyles(wb, styles));
  738. styles.putAll(annotationDataStyles(wb));
  739. return styles;
  740. }
  741. /**
  742. * 根据Excel注解创建表格头样式
  743. *
  744. * @param wb 工作薄对象
  745. * @return 自定义样式列表
  746. */
  747. private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles)
  748. {
  749. Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>();
  750. for (Object[] os : fields)
  751. {
  752. Excel excel = (Excel) os[1];
  753. String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor());
  754. if (!headerStyles.containsKey(key))
  755. {
  756. CellStyle style = wb.createCellStyle();
  757. style = wb.createCellStyle();
  758. style.cloneStyleFrom(styles.get("data"));
  759. style.setAlignment(HorizontalAlignment.CENTER);
  760. style.setVerticalAlignment(VerticalAlignment.CENTER);
  761. style.setFillForegroundColor(excel.headerBackgroundColor().index);
  762. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  763. Font headerFont = wb.createFont();
  764. headerFont.setFontName("Arial");
  765. headerFont.setFontHeightInPoints((short) 10);
  766. headerFont.setBold(true);
  767. headerFont.setColor(excel.headerColor().index);
  768. style.setFont(headerFont);
  769. headerStyles.put(key, style);
  770. }
  771. }
  772. return headerStyles;
  773. }
  774. /**
  775. * 根据Excel注解创建表格列样式
  776. *
  777. * @param wb 工作薄对象
  778. * @return 自定义样式列表
  779. */
  780. private Map<String, CellStyle> annotationDataStyles(Workbook wb)
  781. {
  782. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  783. for (Object[] os : fields)
  784. {
  785. Excel excel = (Excel) os[1];
  786. String key = StringUtils.format("data_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor());
  787. if (!styles.containsKey(key))
  788. {
  789. CellStyle style = wb.createCellStyle();
  790. style = wb.createCellStyle();
  791. style.setAlignment(excel.align());
  792. style.setVerticalAlignment(VerticalAlignment.CENTER);
  793. style.setBorderRight(BorderStyle.THIN);
  794. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  795. style.setBorderLeft(BorderStyle.THIN);
  796. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  797. style.setBorderTop(BorderStyle.THIN);
  798. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  799. style.setBorderBottom(BorderStyle.THIN);
  800. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  801. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  802. style.setFillForegroundColor(excel.backgroundColor().getIndex());
  803. Font dataFont = wb.createFont();
  804. dataFont.setFontName("Arial");
  805. dataFont.setFontHeightInPoints((short) 10);
  806. dataFont.setColor(excel.color().index);
  807. style.setFont(dataFont);
  808. styles.put(key, style);
  809. }
  810. }
  811. return styles;
  812. }
  813. /**
  814. * 创建单元格
  815. */
  816. public Cell createHeadCell(Excel attr, Row row, int column)
  817. {
  818. // 创建列
  819. Cell cell = row.createCell(column);
  820. // 写入列信息
  821. cell.setCellValue(attr.name());
  822. setDataValidation(attr, row, column);
  823. cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  824. if (isSubList())
  825. {
  826. // 填充默认样式,防止合并单元格样式失效
  827. sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  828. if (attr.needMerge())
  829. {
  830. sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column));
  831. }
  832. }
  833. return cell;
  834. }
  835. /**
  836. * 设置单元格信息
  837. *
  838. * @param value 单元格值
  839. * @param attr 注解相关
  840. * @param cell 单元格信息
  841. */
  842. public void setCellVo(Object value, Excel attr, Cell cell)
  843. {
  844. if (ColumnType.STRING == attr.cellType())
  845. {
  846. String cellValue = Convert.toStr(value);
  847. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  848. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  849. {
  850. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  851. }
  852. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  853. }
  854. else if (ColumnType.NUMERIC == attr.cellType())
  855. {
  856. if (StringUtils.isNotNull(value))
  857. {
  858. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  859. }
  860. }
  861. else if (ColumnType.IMAGE == attr.cellType())
  862. {
  863. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  864. String imagePath = Convert.toStr(value);
  865. if (StringUtils.isNotEmpty(imagePath))
  866. {
  867. byte[] data = ImageUtils.getImage(imagePath);
  868. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  869. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  870. }
  871. }
  872. }
  873. /**
  874. * 获取画布
  875. */
  876. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  877. {
  878. if (sheet.getDrawingPatriarch() == null)
  879. {
  880. sheet.createDrawingPatriarch();
  881. }
  882. return sheet.getDrawingPatriarch();
  883. }
  884. /**
  885. * 获取图片类型,设置图片插入类型
  886. */
  887. public int getImageType(byte[] value)
  888. {
  889. String type = FileTypeUtils.getFileExtendName(value);
  890. if ("JPG".equalsIgnoreCase(type))
  891. {
  892. return Workbook.PICTURE_TYPE_JPEG;
  893. }
  894. else if ("PNG".equalsIgnoreCase(type))
  895. {
  896. return Workbook.PICTURE_TYPE_PNG;
  897. }
  898. return Workbook.PICTURE_TYPE_JPEG;
  899. }
  900. /**
  901. * 创建表格样式
  902. */
  903. public void setDataValidation(Excel attr, Row row, int column)
  904. {
  905. if (attr.name().indexOf("注:") >= 0)
  906. {
  907. sheet.setColumnWidth(column, 6000);
  908. }
  909. else
  910. {
  911. // 设置列宽
  912. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  913. }
  914. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  915. {
  916. // 提示信息或只能选择不能输入的列内容.
  917. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  918. }
  919. }
  920. /**
  921. * 添加单元格
  922. */
  923. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  924. {
  925. Cell cell = null;
  926. try
  927. {
  928. // 设置行高
  929. row.setHeight(maxHeight);
  930. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  931. if (attr.isExport())
  932. {
  933. // 创建cell
  934. cell = row.createCell(column);
  935. if (isSubListValue(vo) && attr.needMerge())
  936. {
  937. CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
  938. sheet.addMergedRegion(cellAddress);
  939. }
  940. cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  941. // 用于读取对象中的属性
  942. Object value = getTargetValue(vo, field, attr);
  943. String dateFormat = attr.dateFormat();
  944. String readConverterExp = attr.readConverterExp();
  945. String separator = attr.separator();
  946. String dictType = attr.dictType();
  947. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  948. {
  949. cell.setCellValue(parseDateToStr(dateFormat, value));
  950. }
  951. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  952. {
  953. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  954. }
  955. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  956. {
  957. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  958. }
  959. else if (value instanceof BigDecimal && -1 != attr.scale())
  960. {
  961. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  962. }
  963. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  964. {
  965. cell.setCellValue(dataFormatHandlerAdapter(value, attr));
  966. }
  967. else
  968. {
  969. // 设置列类型
  970. setCellVo(value, attr, cell);
  971. }
  972. addStatisticsData(column, Convert.toStr(value), attr);
  973. }
  974. }
  975. catch (Exception e)
  976. {
  977. log.error("导出Excel失败{}", e);
  978. }
  979. return cell;
  980. }
  981. /**
  982. * 设置 POI XSSFSheet 单元格提示或选择框
  983. *
  984. * @param sheet 表单
  985. * @param textlist 下拉框显示的内容
  986. * @param promptContent 提示内容
  987. * @param firstRow 开始行
  988. * @param endRow 结束行
  989. * @param firstCol 开始列
  990. * @param endCol 结束列
  991. */
  992. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  993. int firstCol, int endCol)
  994. {
  995. DataValidationHelper helper = sheet.getDataValidationHelper();
  996. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  997. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  998. DataValidation dataValidation = helper.createValidation(constraint, regions);
  999. if (StringUtils.isNotEmpty(promptContent))
  1000. {
  1001. // 如果设置了提示信息则鼠标放上去提示
  1002. dataValidation.createPromptBox("", promptContent);
  1003. dataValidation.setShowPromptBox(true);
  1004. }
  1005. // 处理Excel兼容性问题
  1006. if (dataValidation instanceof XSSFDataValidation)
  1007. {
  1008. dataValidation.setSuppressDropDownArrow(true);
  1009. dataValidation.setShowErrorBox(true);
  1010. }
  1011. else
  1012. {
  1013. dataValidation.setSuppressDropDownArrow(false);
  1014. }
  1015. sheet.addValidationData(dataValidation);
  1016. }
  1017. /**
  1018. * 解析导出值 0=男,1=女,2=未知
  1019. *
  1020. * @param propertyValue 参数值
  1021. * @param converterExp 翻译注解
  1022. * @param separator 分隔符
  1023. * @return 解析后值
  1024. */
  1025. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1026. {
  1027. StringBuilder propertyString = new StringBuilder();
  1028. String[] convertSource = converterExp.split(",");
  1029. for (String item : convertSource)
  1030. {
  1031. String[] itemArray = item.split("=");
  1032. if (StringUtils.containsAny(propertyValue, separator))
  1033. {
  1034. for (String value : propertyValue.split(separator))
  1035. {
  1036. if (itemArray[0].equals(value))
  1037. {
  1038. propertyString.append(itemArray[1] + separator);
  1039. break;
  1040. }
  1041. }
  1042. }
  1043. else
  1044. {
  1045. if (itemArray[0].equals(propertyValue))
  1046. {
  1047. return itemArray[1];
  1048. }
  1049. }
  1050. }
  1051. return StringUtils.stripEnd(propertyString.toString(), separator);
  1052. }
  1053. /**
  1054. * 反向解析值 男=0,女=1,未知=2
  1055. *
  1056. * @param propertyValue 参数值
  1057. * @param converterExp 翻译注解
  1058. * @param separator 分隔符
  1059. * @return 解析后值
  1060. */
  1061. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1062. {
  1063. StringBuilder propertyString = new StringBuilder();
  1064. String[] convertSource = converterExp.split(",");
  1065. for (String item : convertSource)
  1066. {
  1067. String[] itemArray = item.split("=");
  1068. if (StringUtils.containsAny(propertyValue, separator))
  1069. {
  1070. for (String value : propertyValue.split(separator))
  1071. {
  1072. if (itemArray[1].equals(value))
  1073. {
  1074. propertyString.append(itemArray[0] + separator);
  1075. break;
  1076. }
  1077. }
  1078. }
  1079. else
  1080. {
  1081. if (itemArray[1].equals(propertyValue))
  1082. {
  1083. return itemArray[0];
  1084. }
  1085. }
  1086. }
  1087. return StringUtils.stripEnd(propertyString.toString(), separator);
  1088. }
  1089. /**
  1090. * 解析字典值
  1091. *
  1092. * @param dictValue 字典值
  1093. * @param dictType 字典类型
  1094. * @param separator 分隔符
  1095. * @return 字典标签
  1096. */
  1097. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1098. {
  1099. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1100. }
  1101. /**
  1102. * 反向解析值字典值
  1103. *
  1104. * @param dictLabel 字典标签
  1105. * @param dictType 字典类型
  1106. * @param separator 分隔符
  1107. * @return 字典值
  1108. */
  1109. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1110. {
  1111. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1112. }
  1113. /**
  1114. * 数据处理器
  1115. *
  1116. * @param value 数据值
  1117. * @param excel 数据注解
  1118. * @return
  1119. */
  1120. public String dataFormatHandlerAdapter(Object value, Excel excel)
  1121. {
  1122. try
  1123. {
  1124. Object instance = excel.handler().newInstance();
  1125. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
  1126. value = formatMethod.invoke(instance, value, excel.args());
  1127. }
  1128. catch (Exception e)
  1129. {
  1130. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1131. }
  1132. return Convert.toStr(value);
  1133. }
  1134. /**
  1135. * 合计统计信息
  1136. */
  1137. private void addStatisticsData(Integer index, String text, Excel entity)
  1138. {
  1139. if (entity != null && entity.isStatistics())
  1140. {
  1141. Double temp = 0D;
  1142. if (!statistics.containsKey(index))
  1143. {
  1144. statistics.put(index, temp);
  1145. }
  1146. try
  1147. {
  1148. temp = Double.valueOf(text);
  1149. }
  1150. catch (NumberFormatException e)
  1151. {
  1152. }
  1153. statistics.put(index, statistics.get(index) + temp);
  1154. }
  1155. }
  1156. /**
  1157. * 创建统计行
  1158. */
  1159. public void addStatisticsRow()
  1160. {
  1161. if (statistics.size() > 0)
  1162. {
  1163. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1164. Set<Integer> keys = statistics.keySet();
  1165. Cell cell = row.createCell(0);
  1166. cell.setCellStyle(styles.get("total"));
  1167. cell.setCellValue("合计");
  1168. for (Integer key : keys)
  1169. {
  1170. cell = row.createCell(key);
  1171. cell.setCellStyle(styles.get("total"));
  1172. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1173. }
  1174. statistics.clear();
  1175. }
  1176. }
  1177. /**
  1178. * 编码文件名
  1179. */
  1180. public String encodingFilename(String filename)
  1181. {
  1182. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  1183. return filename;
  1184. }
  1185. /**
  1186. * 获取下载路径
  1187. *
  1188. * @param filename 文件名称
  1189. */
  1190. public String getAbsoluteFile(String filename)
  1191. {
  1192. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1193. File desc = new File(downloadPath);
  1194. if (!desc.getParentFile().exists())
  1195. {
  1196. desc.getParentFile().mkdirs();
  1197. }
  1198. return downloadPath;
  1199. }
  1200. /**
  1201. * 获取bean中的属性值
  1202. *
  1203. * @param vo 实体对象
  1204. * @param field 字段
  1205. * @param excel 注解
  1206. * @return 最终的属性值
  1207. * @throws Exception
  1208. */
  1209. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1210. {
  1211. Object o = field.get(vo);
  1212. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1213. {
  1214. String target = excel.targetAttr();
  1215. if (target.contains("."))
  1216. {
  1217. String[] targets = target.split("[.]");
  1218. for (String name : targets)
  1219. {
  1220. o = getValue(o, name);
  1221. }
  1222. }
  1223. else
  1224. {
  1225. o = getValue(o, target);
  1226. }
  1227. }
  1228. return o;
  1229. }
  1230. /**
  1231. * 以类的属性的get方法方法形式获取值
  1232. *
  1233. * @param o
  1234. * @param name
  1235. * @return value
  1236. * @throws Exception
  1237. */
  1238. private Object getValue(Object o, String name) throws Exception
  1239. {
  1240. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1241. {
  1242. Class<?> clazz = o.getClass();
  1243. Field field = clazz.getDeclaredField(name);
  1244. field.setAccessible(true);
  1245. o = field.get(o);
  1246. }
  1247. return o;
  1248. }
  1249. /**
  1250. * 得到所有定义字段
  1251. */
  1252. private void createExcelField()
  1253. {
  1254. this.fields = getFields();
  1255. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1256. this.maxHeight = getRowHeight();
  1257. }
  1258. /**
  1259. * 获取字段注解信息
  1260. */
  1261. public List<Object[]> getFields()
  1262. {
  1263. List<Object[]> fields = new ArrayList<Object[]>();
  1264. List<Field> tempFields = new ArrayList<>();
  1265. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1266. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1267. for (Field field : tempFields)
  1268. {
  1269. if (!ArrayUtils.contains(this.excludeFields, field.getName()))
  1270. {
  1271. // 单注解
  1272. if (field.isAnnotationPresent(Excel.class))
  1273. {
  1274. Excel attr = field.getAnnotation(Excel.class);
  1275. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1276. {
  1277. field.setAccessible(true);
  1278. fields.add(new Object[] { field, attr });
  1279. }
  1280. if (Collection.class.isAssignableFrom(field.getType()))
  1281. {
  1282. subMethod = getSubMethod(field.getName(), clazz);
  1283. ParameterizedType pt = (ParameterizedType) field.getGenericType();
  1284. Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
  1285. this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
  1286. }
  1287. }
  1288. // 多注解
  1289. if (field.isAnnotationPresent(Excels.class))
  1290. {
  1291. Excels attrs = field.getAnnotation(Excels.class);
  1292. Excel[] excels = attrs.value();
  1293. for (Excel attr : excels)
  1294. {
  1295. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1296. {
  1297. field.setAccessible(true);
  1298. fields.add(new Object[] { field, attr });
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. return fields;
  1305. }
  1306. /**
  1307. * 根据注解获取最大行高
  1308. */
  1309. public short getRowHeight()
  1310. {
  1311. double maxHeight = 0;
  1312. for (Object[] os : this.fields)
  1313. {
  1314. Excel excel = (Excel) os[1];
  1315. maxHeight = Math.max(maxHeight, excel.height());
  1316. }
  1317. return (short) (maxHeight * 20);
  1318. }
  1319. /**
  1320. * 创建一个工作簿
  1321. */
  1322. public void createWorkbook()
  1323. {
  1324. this.wb = new SXSSFWorkbook(500);
  1325. this.sheet = wb.createSheet();
  1326. wb.setSheetName(0, sheetName);
  1327. this.styles = createStyles(wb);
  1328. }
  1329. /**
  1330. * 创建工作表
  1331. *
  1332. * @param sheetNo sheet数量
  1333. * @param index 序号
  1334. */
  1335. public void createSheet(int sheetNo, int index)
  1336. {
  1337. // 设置工作表的名称.
  1338. if (sheetNo > 1 && index > 0)
  1339. {
  1340. this.sheet = wb.createSheet();
  1341. this.createTitle();
  1342. wb.setSheetName(index, sheetName + index);
  1343. }
  1344. }
  1345. /**
  1346. * 获取单元格值
  1347. *
  1348. * @param row 获取的行
  1349. * @param column 获取单元格列号
  1350. * @return 单元格值
  1351. */
  1352. public Object getCellValue(Row row, int column)
  1353. {
  1354. if (row == null)
  1355. {
  1356. return row;
  1357. }
  1358. Object val = "";
  1359. try
  1360. {
  1361. Cell cell = row.getCell(column);
  1362. if (StringUtils.isNotNull(cell))
  1363. {
  1364. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1365. {
  1366. val = cell.getNumericCellValue();
  1367. if (DateUtil.isCellDateFormatted(cell))
  1368. {
  1369. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1370. }
  1371. else
  1372. {
  1373. if ((Double) val % 1 != 0)
  1374. {
  1375. val = new BigDecimal(val.toString());
  1376. }
  1377. else
  1378. {
  1379. val = new DecimalFormat("0").format(val);
  1380. }
  1381. }
  1382. }
  1383. else if (cell.getCellType() == CellType.STRING)
  1384. {
  1385. val = cell.getStringCellValue();
  1386. }
  1387. else if (cell.getCellType() == CellType.BOOLEAN)
  1388. {
  1389. val = cell.getBooleanCellValue();
  1390. }
  1391. else if (cell.getCellType() == CellType.ERROR)
  1392. {
  1393. val = cell.getErrorCellValue();
  1394. }
  1395. }
  1396. }
  1397. catch (Exception e)
  1398. {
  1399. return val;
  1400. }
  1401. return val;
  1402. }
  1403. /**
  1404. * 判断是否是空行
  1405. *
  1406. * @param row 判断的行
  1407. * @return
  1408. */
  1409. private boolean isRowEmpty(Row row)
  1410. {
  1411. if (row == null)
  1412. {
  1413. return true;
  1414. }
  1415. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1416. {
  1417. Cell cell = row.getCell(i);
  1418. if (cell != null && cell.getCellType() != CellType.BLANK)
  1419. {
  1420. return false;
  1421. }
  1422. }
  1423. return true;
  1424. }
  1425. /**
  1426. * 获取Excel2003图片
  1427. *
  1428. * @param sheet 当前sheet对象
  1429. * @param workbook 工作簿对象
  1430. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1431. */
  1432. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1433. {
  1434. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1435. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1436. if (!pictures.isEmpty())
  1437. {
  1438. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1439. {
  1440. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1441. if (shape instanceof HSSFPicture)
  1442. {
  1443. HSSFPicture pic = (HSSFPicture) shape;
  1444. int pictureIndex = pic.getPictureIndex() - 1;
  1445. HSSFPictureData picData = pictures.get(pictureIndex);
  1446. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
  1447. sheetIndexPicMap.put(picIndex, picData);
  1448. }
  1449. }
  1450. return sheetIndexPicMap;
  1451. }
  1452. else
  1453. {
  1454. return sheetIndexPicMap;
  1455. }
  1456. }
  1457. /**
  1458. * 获取Excel2007图片
  1459. *
  1460. * @param sheet 当前sheet对象
  1461. * @param workbook 工作簿对象
  1462. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1463. */
  1464. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1465. {
  1466. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1467. for (POIXMLDocumentPart dr : sheet.getRelations())
  1468. {
  1469. if (dr instanceof XSSFDrawing)
  1470. {
  1471. XSSFDrawing drawing = (XSSFDrawing) dr;
  1472. List<XSSFShape> shapes = drawing.getShapes();
  1473. for (XSSFShape shape : shapes)
  1474. {
  1475. if (shape instanceof XSSFPicture)
  1476. {
  1477. XSSFPicture pic = (XSSFPicture) shape;
  1478. XSSFClientAnchor anchor = pic.getPreferredSize();
  1479. CTMarker ctMarker = anchor.getFrom();
  1480. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1481. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1482. }
  1483. }
  1484. }
  1485. }
  1486. return sheetIndexPicMap;
  1487. }
  1488. /**
  1489. * 格式化不同类型的日期对象
  1490. *
  1491. * @param dateFormat 日期格式
  1492. * @param val 被格式化的日期对象
  1493. * @return 格式化后的日期字符
  1494. */
  1495. public String parseDateToStr(String dateFormat, Object val)
  1496. {
  1497. if (val == null)
  1498. {
  1499. return "";
  1500. }
  1501. String str;
  1502. if (val instanceof Date)
  1503. {
  1504. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1505. }
  1506. else if (val instanceof LocalDateTime)
  1507. {
  1508. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1509. }
  1510. else if (val instanceof LocalDate)
  1511. {
  1512. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1513. }
  1514. else
  1515. {
  1516. str = val.toString();
  1517. }
  1518. return str;
  1519. }
  1520. /**
  1521. * 是否有对象的子列表
  1522. */
  1523. public boolean isSubList()
  1524. {
  1525. return StringUtils.isNotNull(subFields) && subFields.size() > 0;
  1526. }
  1527. /**
  1528. * 是否有对象的子列表,集合不为空
  1529. */
  1530. public boolean isSubListValue(T vo)
  1531. {
  1532. return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0;
  1533. }
  1534. /**
  1535. * 获取集合的值
  1536. */
  1537. public Collection<?> getListCellValue(Object obj)
  1538. {
  1539. Object value;
  1540. try
  1541. {
  1542. value = subMethod.invoke(obj, new Object[] {});
  1543. }
  1544. catch (Exception e)
  1545. {
  1546. return new ArrayList<Object>();
  1547. }
  1548. return (Collection<?>) value;
  1549. }
  1550. /**
  1551. * 获取对象的子列表方法
  1552. *
  1553. * @param name 名称
  1554. * @param pojoClass 类对象
  1555. * @return 子列表方法
  1556. */
  1557. public Method getSubMethod(String name, Class<?> pojoClass)
  1558. {
  1559. StringBuffer getMethodName = new StringBuffer("get");
  1560. getMethodName.append(name.substring(0, 1).toUpperCase());
  1561. getMethodName.append(name.substring(1));
  1562. Method method = null;
  1563. try
  1564. {
  1565. method = pojoClass.getMethod(getMethodName.toString(), new Class[] {});
  1566. }
  1567. catch (Exception e)
  1568. {
  1569. log.error("获取对象异常{}", e.getMessage());
  1570. }
  1571. return method;
  1572. }
  1573. }