ExcelUtil.java 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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.math.BigDecimal;
  9. import java.text.DecimalFormat;
  10. import java.util.ArrayList;
  11. import java.util.Arrays;
  12. import java.util.Comparator;
  13. import java.util.Date;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Set;
  18. import java.util.UUID;
  19. import java.util.stream.Collectors;
  20. import javax.servlet.http.HttpServletResponse;
  21. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  22. import org.apache.poi.hssf.usermodel.HSSFPicture;
  23. import org.apache.poi.hssf.usermodel.HSSFPictureData;
  24. import org.apache.poi.hssf.usermodel.HSSFShape;
  25. import org.apache.poi.hssf.usermodel.HSSFSheet;
  26. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  27. import org.apache.poi.ooxml.POIXMLDocumentPart;
  28. import org.apache.poi.ss.usermodel.BorderStyle;
  29. import org.apache.poi.ss.usermodel.Cell;
  30. import org.apache.poi.ss.usermodel.CellStyle;
  31. import org.apache.poi.ss.usermodel.CellType;
  32. import org.apache.poi.ss.usermodel.ClientAnchor;
  33. import org.apache.poi.ss.usermodel.DataValidation;
  34. import org.apache.poi.ss.usermodel.DataValidationConstraint;
  35. import org.apache.poi.ss.usermodel.DataValidationHelper;
  36. import org.apache.poi.ss.usermodel.DateUtil;
  37. import org.apache.poi.ss.usermodel.Drawing;
  38. import org.apache.poi.ss.usermodel.FillPatternType;
  39. import org.apache.poi.ss.usermodel.Font;
  40. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  41. import org.apache.poi.ss.usermodel.IndexedColors;
  42. import org.apache.poi.ss.usermodel.PictureData;
  43. import org.apache.poi.ss.usermodel.Row;
  44. import org.apache.poi.ss.usermodel.Sheet;
  45. import org.apache.poi.ss.usermodel.VerticalAlignment;
  46. import org.apache.poi.ss.usermodel.Workbook;
  47. import org.apache.poi.ss.usermodel.WorkbookFactory;
  48. import org.apache.poi.ss.util.CellRangeAddressList;
  49. import org.apache.poi.util.IOUtils;
  50. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  51. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  52. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  53. import org.apache.poi.xssf.usermodel.XSSFDrawing;
  54. import org.apache.poi.xssf.usermodel.XSSFPicture;
  55. import org.apache.poi.xssf.usermodel.XSSFShape;
  56. import org.apache.poi.xssf.usermodel.XSSFSheet;
  57. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  58. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  59. import org.slf4j.Logger;
  60. import org.slf4j.LoggerFactory;
  61. import com.ruoyi.common.annotation.Excel;
  62. import com.ruoyi.common.annotation.Excel.ColumnType;
  63. import com.ruoyi.common.annotation.Excel.Type;
  64. import com.ruoyi.common.annotation.Excels;
  65. import com.ruoyi.common.config.RuoYiConfig;
  66. import com.ruoyi.common.core.domain.AjaxResult;
  67. import com.ruoyi.common.core.text.Convert;
  68. import com.ruoyi.common.exception.UtilException;
  69. import com.ruoyi.common.utils.DateUtils;
  70. import com.ruoyi.common.utils.DictUtils;
  71. import com.ruoyi.common.utils.StringUtils;
  72. import com.ruoyi.common.utils.file.FileTypeUtils;
  73. import com.ruoyi.common.utils.file.FileUtils;
  74. import com.ruoyi.common.utils.file.ImageUtils;
  75. import com.ruoyi.common.utils.reflect.ReflectUtils;
  76. /**
  77. * Excel相关处理
  78. *
  79. * @author ruoyi
  80. */
  81. public class ExcelUtil<T>
  82. {
  83. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  84. /**
  85. * Excel sheet最大行数,默认65536
  86. */
  87. public static final int sheetSize = 65536;
  88. /**
  89. * 工作表名称
  90. */
  91. private String sheetName;
  92. /**
  93. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  94. */
  95. private Type type;
  96. /**
  97. * 工作薄对象
  98. */
  99. private Workbook wb;
  100. /**
  101. * 工作表对象
  102. */
  103. private Sheet sheet;
  104. /**
  105. * 样式列表
  106. */
  107. private Map<String, CellStyle> styles;
  108. /**
  109. * 导入导出数据列表
  110. */
  111. private List<T> list;
  112. /**
  113. * 注解列表
  114. */
  115. private List<Object[]> fields;
  116. /**
  117. * 最大高度
  118. */
  119. private short maxHeight;
  120. /**
  121. * 统计列表
  122. */
  123. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  124. /**
  125. * 数字格式
  126. */
  127. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  128. /**
  129. * 实体对象
  130. */
  131. public Class<T> clazz;
  132. public ExcelUtil(Class<T> clazz)
  133. {
  134. this.clazz = clazz;
  135. }
  136. public void init(List<T> list, String sheetName, Type type)
  137. {
  138. if (list == null)
  139. {
  140. list = new ArrayList<T>();
  141. }
  142. this.list = list;
  143. this.sheetName = sheetName;
  144. this.type = type;
  145. createExcelField();
  146. createWorkbook();
  147. }
  148. /**
  149. * 对excel表单默认第一个索引名转换成list
  150. *
  151. * @param is 输入流
  152. * @return 转换后集合
  153. */
  154. public List<T> importExcel(InputStream is) throws Exception
  155. {
  156. return importExcel(StringUtils.EMPTY, is);
  157. }
  158. /**
  159. * 对excel表单指定表格索引名转换成list
  160. *
  161. * @param sheetName 表格索引名
  162. * @param is 输入流
  163. * @return 转换后集合
  164. */
  165. public List<T> importExcel(String sheetName, InputStream is) throws Exception
  166. {
  167. this.type = Type.IMPORT;
  168. this.wb = WorkbookFactory.create(is);
  169. List<T> list = new ArrayList<T>();
  170. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
  171. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
  172. if (sheet == null)
  173. {
  174. throw new IOException("文件sheet不存在");
  175. }
  176. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
  177. Map<String, PictureData> pictures;
  178. if (isXSSFWorkbook)
  179. {
  180. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
  181. }
  182. else
  183. {
  184. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
  185. }
  186. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
  187. int rows = sheet.getLastRowNum();
  188. if (rows > 0)
  189. {
  190. // 定义一个map用于存放excel列的序号和field.
  191. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  192. // 获取表头
  193. Row heard = sheet.getRow(0);
  194. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  195. {
  196. Cell cell = heard.getCell(i);
  197. if (StringUtils.isNotNull(cell))
  198. {
  199. String value = this.getCellValue(heard, i).toString();
  200. cellMap.put(value, i);
  201. }
  202. else
  203. {
  204. cellMap.put(null, i);
  205. }
  206. }
  207. // 有数据时才处理 得到类的所有field.
  208. Field[] allFields = clazz.getDeclaredFields();
  209. // 定义一个map用于存放列的序号和field.
  210. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
  211. for (int col = 0; col < allFields.length; col++)
  212. {
  213. Field field = allFields[col];
  214. Excel attr = field.getAnnotation(Excel.class);
  215. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  216. {
  217. // 设置类的私有字段属性可访问.
  218. field.setAccessible(true);
  219. Integer column = cellMap.get(attr.name());
  220. if (column != null)
  221. {
  222. fieldsMap.put(column, field);
  223. }
  224. }
  225. }
  226. for (int i = 1; i <= rows; i++)
  227. {
  228. // 从第2行开始取数据,默认第一行是表头.
  229. Row row = sheet.getRow(i);
  230. // 判断当前行是否是空行
  231. if (isRowEmpty(row))
  232. {
  233. continue;
  234. }
  235. T entity = null;
  236. for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet())
  237. {
  238. Object val = this.getCellValue(row, entry.getKey());
  239. // 如果不存在实例则新建.
  240. entity = (entity == null ? clazz.newInstance() : entity);
  241. // 从map中得到对应列的field.
  242. Field field = fieldsMap.get(entry.getKey());
  243. // 取得类型,并根据对象类型设置值.
  244. Class<?> fieldType = field.getType();
  245. if (String.class == fieldType)
  246. {
  247. String s = Convert.toStr(val);
  248. if (StringUtils.endsWith(s, ".0"))
  249. {
  250. val = StringUtils.substringBefore(s, ".0");
  251. }
  252. else
  253. {
  254. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  255. if (StringUtils.isNotEmpty(dateFormat))
  256. {
  257. val = DateUtils.parseDateToStr(dateFormat, (Date) val);
  258. }
  259. else
  260. {
  261. val = Convert.toStr(val);
  262. }
  263. }
  264. }
  265. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  266. {
  267. val = Convert.toInt(val);
  268. }
  269. else if (Long.TYPE == fieldType || Long.class == fieldType)
  270. {
  271. val = Convert.toLong(val);
  272. }
  273. else if (Double.TYPE == fieldType || Double.class == fieldType)
  274. {
  275. val = Convert.toDouble(val);
  276. }
  277. else if (Float.TYPE == fieldType || Float.class == fieldType)
  278. {
  279. val = Convert.toFloat(val);
  280. }
  281. else if (BigDecimal.class == fieldType)
  282. {
  283. val = Convert.toBigDecimal(val);
  284. }
  285. else if (Date.class == fieldType)
  286. {
  287. if (val instanceof String)
  288. {
  289. val = DateUtils.parseDate(val);
  290. }
  291. else if (val instanceof Double)
  292. {
  293. val = DateUtil.getJavaDate((Double) val);
  294. }
  295. }
  296. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  297. {
  298. val = Convert.toBool(val, false);
  299. }
  300. if (StringUtils.isNotNull(fieldType))
  301. {
  302. Excel attr = field.getAnnotation(Excel.class);
  303. String propertyName = field.getName();
  304. if (StringUtils.isNotEmpty(attr.targetAttr()))
  305. {
  306. propertyName = field.getName() + "." + attr.targetAttr();
  307. }
  308. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  309. {
  310. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  311. }
  312. else if (StringUtils.isNotEmpty(attr.dictType()))
  313. {
  314. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  315. }
  316. else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
  317. {
  318. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
  319. if (image == null)
  320. {
  321. val = "";
  322. }
  323. else
  324. {
  325. byte[] data = image.getData();
  326. val = FileUtils.writeImportBytes(data);
  327. }
  328. }
  329. ReflectUtils.invokeSetter(entity, propertyName, val);
  330. }
  331. }
  332. list.add(entity);
  333. }
  334. }
  335. return list;
  336. }
  337. /**
  338. * 对list数据源将其里面的数据导入到excel表单
  339. *
  340. * @param list 导出数据集合
  341. * @param sheetName 工作表的名称
  342. * @return 结果
  343. */
  344. public AjaxResult exportExcel(List<T> list, String sheetName)
  345. {
  346. this.init(list, sheetName, Type.EXPORT);
  347. return exportExcel();
  348. }
  349. /**
  350. * 对list数据源将其里面的数据导入到excel表单
  351. *
  352. * @param response 返回数据
  353. * @param list 导出数据集合
  354. * @param sheetName 工作表的名称
  355. * @return 结果
  356. * @throws IOException
  357. */
  358. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) throws IOException
  359. {
  360. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  361. response.setCharacterEncoding("utf-8");
  362. this.init(list, sheetName, Type.EXPORT);
  363. exportExcel(response.getOutputStream());
  364. }
  365. /**
  366. * 对list数据源将其里面的数据导入到excel表单
  367. *
  368. * @param sheetName 工作表的名称
  369. * @return 结果
  370. */
  371. public AjaxResult importTemplateExcel(String sheetName)
  372. {
  373. this.init(null, sheetName, Type.IMPORT);
  374. return exportExcel();
  375. }
  376. /**
  377. * 对list数据源将其里面的数据导入到excel表单
  378. *
  379. * @param sheetName 工作表的名称
  380. * @return 结果
  381. */
  382. public void importTemplateExcel(HttpServletResponse response, String sheetName) throws IOException
  383. {
  384. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  385. response.setCharacterEncoding("utf-8");
  386. this.init(null, sheetName, Type.IMPORT);
  387. exportExcel(response.getOutputStream());
  388. }
  389. /**
  390. * 对list数据源将其里面的数据导入到excel表单
  391. *
  392. * @return 结果
  393. */
  394. public void exportExcel(OutputStream out)
  395. {
  396. try
  397. {
  398. writeSheet();
  399. wb.write(out);
  400. }
  401. catch (Exception e)
  402. {
  403. log.error("导出Excel异常{}", e.getMessage());
  404. }
  405. finally
  406. {
  407. IOUtils.closeQuietly(wb);
  408. IOUtils.closeQuietly(out);
  409. }
  410. }
  411. /**
  412. * 对list数据源将其里面的数据导入到excel表单
  413. *
  414. * @return 结果
  415. */
  416. public AjaxResult exportExcel()
  417. {
  418. OutputStream out = null;
  419. try
  420. {
  421. writeSheet();
  422. String filename = encodingFilename(sheetName);
  423. out = new FileOutputStream(getAbsoluteFile(filename));
  424. wb.write(out);
  425. return AjaxResult.success(filename);
  426. }
  427. catch (Exception e)
  428. {
  429. log.error("导出Excel异常{}", e.getMessage());
  430. throw new UtilException("导出Excel失败,请联系网站管理员!");
  431. }
  432. finally
  433. {
  434. IOUtils.closeQuietly(wb);
  435. IOUtils.closeQuietly(out);
  436. }
  437. }
  438. /**
  439. * 创建写入数据到Sheet
  440. */
  441. public void writeSheet()
  442. {
  443. // 取出一共有多少个sheet.
  444. double sheetNo = Math.ceil(list.size() / sheetSize);
  445. for (int index = 0; index <= sheetNo; index++)
  446. {
  447. createSheet(sheetNo, index);
  448. // 产生一行
  449. Row row = sheet.createRow(0);
  450. int column = 0;
  451. // 写入各个字段的列头名称
  452. for (Object[] os : fields)
  453. {
  454. Excel excel = (Excel) os[1];
  455. this.createCell(excel, row, column++);
  456. }
  457. if (Type.EXPORT.equals(type))
  458. {
  459. fillExcelData(index, row);
  460. addStatisticsRow();
  461. }
  462. }
  463. }
  464. /**
  465. * 填充excel数据
  466. *
  467. * @param index 序号
  468. * @param row 单元格行
  469. */
  470. public void fillExcelData(int index, Row row)
  471. {
  472. int startNo = index * sheetSize;
  473. int endNo = Math.min(startNo + sheetSize, list.size());
  474. for (int i = startNo; i < endNo; i++)
  475. {
  476. row = sheet.createRow(i + 1 - startNo);
  477. // 得到导出对象.
  478. T vo = (T) list.get(i);
  479. int column = 0;
  480. for (Object[] os : fields)
  481. {
  482. Field field = (Field) os[0];
  483. Excel excel = (Excel) os[1];
  484. // 设置实体类私有属性可访问
  485. field.setAccessible(true);
  486. this.addCell(excel, row, vo, field, column++);
  487. }
  488. }
  489. }
  490. /**
  491. * 创建表格样式
  492. *
  493. * @param wb 工作薄对象
  494. * @return 样式列表
  495. */
  496. private Map<String, CellStyle> createStyles(Workbook wb)
  497. {
  498. // 写入各条记录,每条记录对应excel表中的一行
  499. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  500. CellStyle style = wb.createCellStyle();
  501. style.setAlignment(HorizontalAlignment.CENTER);
  502. style.setVerticalAlignment(VerticalAlignment.CENTER);
  503. style.setBorderRight(BorderStyle.THIN);
  504. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  505. style.setBorderLeft(BorderStyle.THIN);
  506. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  507. style.setBorderTop(BorderStyle.THIN);
  508. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  509. style.setBorderBottom(BorderStyle.THIN);
  510. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  511. Font dataFont = wb.createFont();
  512. dataFont.setFontName("Arial");
  513. dataFont.setFontHeightInPoints((short) 10);
  514. style.setFont(dataFont);
  515. styles.put("data", style);
  516. style = wb.createCellStyle();
  517. style.cloneStyleFrom(styles.get("data"));
  518. style.setAlignment(HorizontalAlignment.CENTER);
  519. style.setVerticalAlignment(VerticalAlignment.CENTER);
  520. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  521. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  522. Font headerFont = wb.createFont();
  523. headerFont.setFontName("Arial");
  524. headerFont.setFontHeightInPoints((short) 10);
  525. headerFont.setBold(true);
  526. headerFont.setColor(IndexedColors.WHITE.getIndex());
  527. style.setFont(headerFont);
  528. styles.put("header", style);
  529. style = wb.createCellStyle();
  530. style.setAlignment(HorizontalAlignment.CENTER);
  531. style.setVerticalAlignment(VerticalAlignment.CENTER);
  532. Font totalFont = wb.createFont();
  533. totalFont.setFontName("Arial");
  534. totalFont.setFontHeightInPoints((short) 10);
  535. style.setFont(totalFont);
  536. styles.put("total", style);
  537. style = wb.createCellStyle();
  538. style.cloneStyleFrom(styles.get("data"));
  539. style.setAlignment(HorizontalAlignment.LEFT);
  540. styles.put("data1", style);
  541. style = wb.createCellStyle();
  542. style.cloneStyleFrom(styles.get("data"));
  543. style.setAlignment(HorizontalAlignment.CENTER);
  544. styles.put("data2", style);
  545. style = wb.createCellStyle();
  546. style.cloneStyleFrom(styles.get("data"));
  547. style.setAlignment(HorizontalAlignment.RIGHT);
  548. styles.put("data3", style);
  549. return styles;
  550. }
  551. /**
  552. * 创建单元格
  553. */
  554. public Cell createCell(Excel attr, Row row, int column)
  555. {
  556. // 创建列
  557. Cell cell = row.createCell(column);
  558. // 写入列信息
  559. cell.setCellValue(attr.name());
  560. setDataValidation(attr, row, column);
  561. cell.setCellStyle(styles.get("header"));
  562. return cell;
  563. }
  564. /**
  565. * 设置单元格信息
  566. *
  567. * @param value 单元格值
  568. * @param attr 注解相关
  569. * @param cell 单元格信息
  570. */
  571. public void setCellVo(Object value, Excel attr, Cell cell)
  572. {
  573. if (ColumnType.STRING == attr.cellType())
  574. {
  575. cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
  576. }
  577. else if (ColumnType.NUMERIC == attr.cellType())
  578. {
  579. if (StringUtils.isNotNull(value))
  580. {
  581. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  582. }
  583. }
  584. else if (ColumnType.IMAGE == attr.cellType())
  585. {
  586. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  587. String imagePath = Convert.toStr(value);
  588. if (StringUtils.isNotEmpty(imagePath))
  589. {
  590. byte[] data = ImageUtils.getImage(imagePath);
  591. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  592. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  593. }
  594. }
  595. }
  596. /**
  597. * 获取画布
  598. */
  599. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  600. {
  601. if (sheet.getDrawingPatriarch() == null)
  602. {
  603. sheet.createDrawingPatriarch();
  604. }
  605. return sheet.getDrawingPatriarch();
  606. }
  607. /**
  608. * 获取图片类型,设置图片插入类型
  609. */
  610. public int getImageType(byte[] value)
  611. {
  612. String type = FileTypeUtils.getFileExtendName(value);
  613. if ("JPG".equalsIgnoreCase(type))
  614. {
  615. return Workbook.PICTURE_TYPE_JPEG;
  616. }
  617. else if ("PNG".equalsIgnoreCase(type))
  618. {
  619. return Workbook.PICTURE_TYPE_PNG;
  620. }
  621. return Workbook.PICTURE_TYPE_JPEG;
  622. }
  623. /**
  624. * 创建表格样式
  625. */
  626. public void setDataValidation(Excel attr, Row row, int column)
  627. {
  628. if (attr.name().indexOf("注:") >= 0)
  629. {
  630. sheet.setColumnWidth(column, 6000);
  631. }
  632. else
  633. {
  634. // 设置列宽
  635. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  636. }
  637. // 如果设置了提示信息则鼠标放上去提示.
  638. if (StringUtils.isNotEmpty(attr.prompt()))
  639. {
  640. // 这里默认设了2-101列提示.
  641. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
  642. }
  643. // 如果设置了combo属性则本列只能选择不能输入
  644. if (attr.combo().length > 0)
  645. {
  646. // 这里默认设了2-101列只能选择不能输入.
  647. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
  648. }
  649. }
  650. /**
  651. * 添加单元格
  652. */
  653. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  654. {
  655. Cell cell = null;
  656. try
  657. {
  658. // 设置行高
  659. row.setHeight(maxHeight);
  660. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  661. if (attr.isExport())
  662. {
  663. // 创建cell
  664. cell = row.createCell(column);
  665. int align = attr.align().value();
  666. cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
  667. // 用于读取对象中的属性
  668. Object value = getTargetValue(vo, field, attr);
  669. String dateFormat = attr.dateFormat();
  670. String readConverterExp = attr.readConverterExp();
  671. String separator = attr.separator();
  672. String dictType = attr.dictType();
  673. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  674. {
  675. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  676. }
  677. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  678. {
  679. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  680. }
  681. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  682. {
  683. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  684. }
  685. else if (value instanceof BigDecimal && -1 != attr.scale())
  686. {
  687. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  688. }
  689. else
  690. {
  691. // 设置列类型
  692. setCellVo(value, attr, cell);
  693. }
  694. addStatisticsData(column, Convert.toStr(value), attr);
  695. }
  696. }
  697. catch (Exception e)
  698. {
  699. log.error("导出Excel失败{}", e);
  700. }
  701. return cell;
  702. }
  703. /**
  704. * 设置 POI XSSFSheet 单元格提示
  705. *
  706. * @param sheet 表单
  707. * @param promptTitle 提示标题
  708. * @param promptContent 提示内容
  709. * @param firstRow 开始行
  710. * @param endRow 结束行
  711. * @param firstCol 开始列
  712. * @param endCol 结束列
  713. */
  714. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  715. int firstCol, int endCol)
  716. {
  717. DataValidationHelper helper = sheet.getDataValidationHelper();
  718. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  719. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  720. DataValidation dataValidation = helper.createValidation(constraint, regions);
  721. dataValidation.createPromptBox(promptTitle, promptContent);
  722. dataValidation.setShowPromptBox(true);
  723. sheet.addValidationData(dataValidation);
  724. }
  725. /**
  726. * 设置某些列的值只能输入预制的数据,显示下拉框.
  727. *
  728. * @param sheet 要设置的sheet.
  729. * @param textlist 下拉框显示的内容
  730. * @param firstRow 开始行
  731. * @param endRow 结束行
  732. * @param firstCol 开始列
  733. * @param endCol 结束列
  734. * @return 设置好的sheet.
  735. */
  736. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  737. {
  738. DataValidationHelper helper = sheet.getDataValidationHelper();
  739. // 加载下拉列表内容
  740. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  741. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  742. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  743. // 数据有效性对象
  744. DataValidation dataValidation = helper.createValidation(constraint, regions);
  745. // 处理Excel兼容性问题
  746. if (dataValidation instanceof XSSFDataValidation)
  747. {
  748. dataValidation.setSuppressDropDownArrow(true);
  749. dataValidation.setShowErrorBox(true);
  750. }
  751. else
  752. {
  753. dataValidation.setSuppressDropDownArrow(false);
  754. }
  755. sheet.addValidationData(dataValidation);
  756. }
  757. /**
  758. * 解析导出值 0=男,1=女,2=未知
  759. *
  760. * @param propertyValue 参数值
  761. * @param converterExp 翻译注解
  762. * @param separator 分隔符
  763. * @return 解析后值
  764. */
  765. public static String convertByExp(String propertyValue, String converterExp, String separator)
  766. {
  767. StringBuilder propertyString = new StringBuilder();
  768. String[] convertSource = converterExp.split(",");
  769. for (String item : convertSource)
  770. {
  771. String[] itemArray = item.split("=");
  772. if (StringUtils.containsAny(separator, propertyValue))
  773. {
  774. for (String value : propertyValue.split(separator))
  775. {
  776. if (itemArray[0].equals(value))
  777. {
  778. propertyString.append(itemArray[1] + separator);
  779. break;
  780. }
  781. }
  782. }
  783. else
  784. {
  785. if (itemArray[0].equals(propertyValue))
  786. {
  787. return itemArray[1];
  788. }
  789. }
  790. }
  791. return StringUtils.stripEnd(propertyString.toString(), separator);
  792. }
  793. /**
  794. * 反向解析值 男=0,女=1,未知=2
  795. *
  796. * @param propertyValue 参数值
  797. * @param converterExp 翻译注解
  798. * @param separator 分隔符
  799. * @return 解析后值
  800. */
  801. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  802. {
  803. StringBuilder propertyString = new StringBuilder();
  804. String[] convertSource = converterExp.split(",");
  805. for (String item : convertSource)
  806. {
  807. String[] itemArray = item.split("=");
  808. if (StringUtils.containsAny(separator, propertyValue))
  809. {
  810. for (String value : propertyValue.split(separator))
  811. {
  812. if (itemArray[1].equals(value))
  813. {
  814. propertyString.append(itemArray[0] + separator);
  815. break;
  816. }
  817. }
  818. }
  819. else
  820. {
  821. if (itemArray[1].equals(propertyValue))
  822. {
  823. return itemArray[0];
  824. }
  825. }
  826. }
  827. return StringUtils.stripEnd(propertyString.toString(), separator);
  828. }
  829. /**
  830. * 解析字典值
  831. *
  832. * @param dictValue 字典值
  833. * @param dictType 字典类型
  834. * @param separator 分隔符
  835. * @return 字典标签
  836. */
  837. public static String convertDictByExp(String dictValue, String dictType, String separator)
  838. {
  839. return DictUtils.getDictLabel(dictType, dictValue, separator);
  840. }
  841. /**
  842. * 反向解析值字典值
  843. *
  844. * @param dictLabel 字典标签
  845. * @param dictType 字典类型
  846. * @param separator 分隔符
  847. * @return 字典值
  848. */
  849. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  850. {
  851. return DictUtils.getDictValue(dictType, dictLabel, separator);
  852. }
  853. /**
  854. * 合计统计信息
  855. */
  856. private void addStatisticsData(Integer index, String text, Excel entity)
  857. {
  858. if (entity != null && entity.isStatistics())
  859. {
  860. Double temp = 0D;
  861. if (!statistics.containsKey(index))
  862. {
  863. statistics.put(index, temp);
  864. }
  865. try
  866. {
  867. temp = Double.valueOf(text);
  868. }
  869. catch (NumberFormatException e)
  870. {
  871. }
  872. statistics.put(index, statistics.get(index) + temp);
  873. }
  874. }
  875. /**
  876. * 创建统计行
  877. */
  878. public void addStatisticsRow()
  879. {
  880. if (statistics.size() > 0)
  881. {
  882. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  883. Set<Integer> keys = statistics.keySet();
  884. Cell cell = row.createCell(0);
  885. cell.setCellStyle(styles.get("total"));
  886. cell.setCellValue("合计");
  887. for (Integer key : keys)
  888. {
  889. cell = row.createCell(key);
  890. cell.setCellStyle(styles.get("total"));
  891. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  892. }
  893. statistics.clear();
  894. }
  895. }
  896. /**
  897. * 编码文件名
  898. */
  899. public String encodingFilename(String filename)
  900. {
  901. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  902. return filename;
  903. }
  904. /**
  905. * 获取下载路径
  906. *
  907. * @param filename 文件名称
  908. */
  909. public String getAbsoluteFile(String filename)
  910. {
  911. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  912. File desc = new File(downloadPath);
  913. if (!desc.getParentFile().exists())
  914. {
  915. desc.getParentFile().mkdirs();
  916. }
  917. return downloadPath;
  918. }
  919. /**
  920. * 获取bean中的属性值
  921. *
  922. * @param vo 实体对象
  923. * @param field 字段
  924. * @param excel 注解
  925. * @return 最终的属性值
  926. * @throws Exception
  927. */
  928. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  929. {
  930. Object o = field.get(vo);
  931. if (StringUtils.isNotEmpty(excel.targetAttr()))
  932. {
  933. String target = excel.targetAttr();
  934. if (target.indexOf(".") > -1)
  935. {
  936. String[] targets = target.split("[.]");
  937. for (String name : targets)
  938. {
  939. o = getValue(o, name);
  940. }
  941. }
  942. else
  943. {
  944. o = getValue(o, target);
  945. }
  946. }
  947. return o;
  948. }
  949. /**
  950. * 以类的属性的get方法方法形式获取值
  951. *
  952. * @param o
  953. * @param name
  954. * @return value
  955. * @throws Exception
  956. */
  957. private Object getValue(Object o, String name) throws Exception
  958. {
  959. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  960. {
  961. Class<?> clazz = o.getClass();
  962. Field field = clazz.getDeclaredField(name);
  963. field.setAccessible(true);
  964. o = field.get(o);
  965. }
  966. return o;
  967. }
  968. /**
  969. * 得到所有定义字段
  970. */
  971. private void createExcelField()
  972. {
  973. this.fields = new ArrayList<Object[]>();
  974. List<Field> tempFields = new ArrayList<>();
  975. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  976. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  977. for (Field field : tempFields)
  978. {
  979. // 单注解
  980. if (field.isAnnotationPresent(Excel.class))
  981. {
  982. putToField(field, field.getAnnotation(Excel.class));
  983. }
  984. // 多注解
  985. if (field.isAnnotationPresent(Excels.class))
  986. {
  987. Excels attrs = field.getAnnotation(Excels.class);
  988. Excel[] excels = attrs.value();
  989. for (Excel excel : excels)
  990. {
  991. putToField(field, excel);
  992. }
  993. }
  994. }
  995. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  996. this.maxHeight = getRowHeight();
  997. }
  998. /**
  999. * 根据注解获取最大行高
  1000. */
  1001. public short getRowHeight()
  1002. {
  1003. double maxHeight = 0;
  1004. for (Object[] os : this.fields)
  1005. {
  1006. Excel excel = (Excel) os[1];
  1007. maxHeight = maxHeight > excel.height() ? maxHeight : excel.height();
  1008. }
  1009. return (short) (maxHeight * 20);
  1010. }
  1011. /**
  1012. * 放到字段集合中
  1013. */
  1014. private void putToField(Field field, Excel attr)
  1015. {
  1016. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1017. {
  1018. this.fields.add(new Object[] { field, attr });
  1019. }
  1020. }
  1021. /**
  1022. * 创建一个工作簿
  1023. */
  1024. public void createWorkbook()
  1025. {
  1026. this.wb = new SXSSFWorkbook(500);
  1027. }
  1028. /**
  1029. * 创建工作表
  1030. *
  1031. * @param sheetNo sheet数量
  1032. * @param index 序号
  1033. */
  1034. public void createSheet(double sheetNo, int index)
  1035. {
  1036. this.sheet = wb.createSheet();
  1037. this.styles = createStyles(wb);
  1038. // 设置工作表的名称.
  1039. if (sheetNo == 0)
  1040. {
  1041. wb.setSheetName(index, sheetName);
  1042. }
  1043. else
  1044. {
  1045. wb.setSheetName(index, sheetName + index);
  1046. }
  1047. }
  1048. /**
  1049. * 获取单元格值
  1050. *
  1051. * @param row 获取的行
  1052. * @param column 获取单元格列号
  1053. * @return 单元格值
  1054. */
  1055. public Object getCellValue(Row row, int column)
  1056. {
  1057. if (row == null)
  1058. {
  1059. return row;
  1060. }
  1061. Object val = "";
  1062. try
  1063. {
  1064. Cell cell = row.getCell(column);
  1065. if (StringUtils.isNotNull(cell))
  1066. {
  1067. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1068. {
  1069. val = cell.getNumericCellValue();
  1070. if (DateUtil.isCellDateFormatted(cell))
  1071. {
  1072. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1073. }
  1074. else
  1075. {
  1076. if ((Double) val % 1 != 0)
  1077. {
  1078. val = new BigDecimal(val.toString());
  1079. }
  1080. else
  1081. {
  1082. val = new DecimalFormat("0").format(val);
  1083. }
  1084. }
  1085. }
  1086. else if (cell.getCellType() == CellType.STRING)
  1087. {
  1088. val = cell.getStringCellValue();
  1089. }
  1090. else if (cell.getCellType() == CellType.BOOLEAN)
  1091. {
  1092. val = cell.getBooleanCellValue();
  1093. }
  1094. else if (cell.getCellType() == CellType.ERROR)
  1095. {
  1096. val = cell.getErrorCellValue();
  1097. }
  1098. }
  1099. }
  1100. catch (Exception e)
  1101. {
  1102. return val;
  1103. }
  1104. return val;
  1105. }
  1106. /**
  1107. * 判断是否是空行
  1108. *
  1109. * @param row 判断的行
  1110. * @return
  1111. */
  1112. private boolean isRowEmpty(Row row)
  1113. {
  1114. if (row == null)
  1115. {
  1116. return true;
  1117. }
  1118. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1119. {
  1120. Cell cell = row.getCell(i);
  1121. if (cell != null && cell.getCellType() != CellType.BLANK)
  1122. {
  1123. return false;
  1124. }
  1125. }
  1126. return true;
  1127. }
  1128. /**
  1129. * 获取Excel2003图片
  1130. *
  1131. * @param sheet 当前sheet对象
  1132. * @param workbook 工作簿对象
  1133. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1134. */
  1135. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1136. {
  1137. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1138. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1139. if (!pictures.isEmpty())
  1140. {
  1141. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1142. {
  1143. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1144. if (shape instanceof HSSFPicture)
  1145. {
  1146. HSSFPicture pic = (HSSFPicture) shape;
  1147. int pictureIndex = pic.getPictureIndex() - 1;
  1148. HSSFPictureData picData = pictures.get(pictureIndex);
  1149. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
  1150. sheetIndexPicMap.put(picIndex, picData);
  1151. }
  1152. }
  1153. return sheetIndexPicMap;
  1154. }
  1155. else
  1156. {
  1157. return sheetIndexPicMap;
  1158. }
  1159. }
  1160. /**
  1161. * 获取Excel2007图片
  1162. *
  1163. * @param sheet 当前sheet对象
  1164. * @param workbook 工作簿对象
  1165. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1166. */
  1167. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1168. {
  1169. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1170. for (POIXMLDocumentPart dr : sheet.getRelations())
  1171. {
  1172. if (dr instanceof XSSFDrawing)
  1173. {
  1174. XSSFDrawing drawing = (XSSFDrawing) dr;
  1175. List<XSSFShape> shapes = drawing.getShapes();
  1176. for (XSSFShape shape : shapes)
  1177. {
  1178. if (shape instanceof XSSFPicture)
  1179. {
  1180. XSSFPicture pic = (XSSFPicture) shape;
  1181. XSSFClientAnchor anchor = pic.getPreferredSize();
  1182. CTMarker ctMarker = anchor.getFrom();
  1183. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1184. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return sheetIndexPicMap;
  1190. }
  1191. }