ExcelUtil.java 56 KB

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