ExcelUtil.java 61 KB

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