ExcelUtil.java 56 KB

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