ExcelUtil.java 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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.CustomException;
  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. byte[] data = image.getData();
  324. val = FileUtils.writeImportBytes(data);
  325. }
  326. ReflectUtils.invokeSetter(entity, propertyName, val);
  327. }
  328. }
  329. list.add(entity);
  330. }
  331. }
  332. return list;
  333. }
  334. /**
  335. * 对list数据源将其里面的数据导入到excel表单
  336. *
  337. * @param list 导出数据集合
  338. * @param sheetName 工作表的名称
  339. * @return 结果
  340. */
  341. public AjaxResult exportExcel(List<T> list, String sheetName)
  342. {
  343. this.init(list, sheetName, Type.EXPORT);
  344. return exportExcel();
  345. }
  346. /**
  347. * 对list数据源将其里面的数据导入到excel表单
  348. *
  349. * @param response 返回数据
  350. * @param list 导出数据集合
  351. * @param sheetName 工作表的名称
  352. * @return 结果
  353. * @throws IOException
  354. */
  355. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) throws IOException
  356. {
  357. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  358. response.setCharacterEncoding("utf-8");
  359. this.init(list, sheetName, Type.EXPORT);
  360. exportExcel(response.getOutputStream());
  361. }
  362. /**
  363. * 对list数据源将其里面的数据导入到excel表单
  364. *
  365. * @param sheetName 工作表的名称
  366. * @return 结果
  367. */
  368. public AjaxResult importTemplateExcel(String sheetName)
  369. {
  370. this.init(null, sheetName, Type.IMPORT);
  371. return exportExcel();
  372. }
  373. /**
  374. * 对list数据源将其里面的数据导入到excel表单
  375. *
  376. * @param sheetName 工作表的名称
  377. * @return 结果
  378. */
  379. public void importTemplateExcel(HttpServletResponse response, String sheetName) throws IOException
  380. {
  381. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  382. response.setCharacterEncoding("utf-8");
  383. this.init(null, sheetName, Type.IMPORT);
  384. exportExcel(response.getOutputStream());
  385. }
  386. /**
  387. * 对list数据源将其里面的数据导入到excel表单
  388. *
  389. * @return 结果
  390. */
  391. public void exportExcel(OutputStream out)
  392. {
  393. try
  394. {
  395. writeSheet();
  396. wb.write(out);
  397. }
  398. catch (Exception e)
  399. {
  400. log.error("导出Excel异常{}", e.getMessage());
  401. }
  402. finally
  403. {
  404. IOUtils.closeQuietly(wb);
  405. IOUtils.closeQuietly(out);
  406. }
  407. }
  408. /**
  409. * 对list数据源将其里面的数据导入到excel表单
  410. *
  411. * @return 结果
  412. */
  413. public AjaxResult exportExcel()
  414. {
  415. OutputStream out = null;
  416. try
  417. {
  418. writeSheet();
  419. String filename = encodingFilename(sheetName);
  420. out = new FileOutputStream(getAbsoluteFile(filename));
  421. wb.write(out);
  422. return AjaxResult.success(filename);
  423. }
  424. catch (Exception e)
  425. {
  426. log.error("导出Excel异常{}", e.getMessage());
  427. throw new CustomException("导出Excel失败,请联系网站管理员!");
  428. }
  429. finally
  430. {
  431. IOUtils.closeQuietly(wb);
  432. IOUtils.closeQuietly(out);
  433. }
  434. }
  435. /**
  436. * 创建写入数据到Sheet
  437. */
  438. public void writeSheet()
  439. {
  440. // 取出一共有多少个sheet.
  441. double sheetNo = Math.ceil(list.size() / sheetSize);
  442. for (int index = 0; index <= sheetNo; index++)
  443. {
  444. createSheet(sheetNo, index);
  445. // 产生一行
  446. Row row = sheet.createRow(0);
  447. int column = 0;
  448. // 写入各个字段的列头名称
  449. for (Object[] os : fields)
  450. {
  451. Excel excel = (Excel) os[1];
  452. this.createCell(excel, row, column++);
  453. }
  454. if (Type.EXPORT.equals(type))
  455. {
  456. fillExcelData(index, row);
  457. addStatisticsRow();
  458. }
  459. }
  460. }
  461. /**
  462. * 填充excel数据
  463. *
  464. * @param index 序号
  465. * @param row 单元格行
  466. */
  467. public void fillExcelData(int index, Row row)
  468. {
  469. int startNo = index * sheetSize;
  470. int endNo = Math.min(startNo + sheetSize, list.size());
  471. for (int i = startNo; i < endNo; i++)
  472. {
  473. row = sheet.createRow(i + 1 - startNo);
  474. // 得到导出对象.
  475. T vo = (T) list.get(i);
  476. int column = 0;
  477. for (Object[] os : fields)
  478. {
  479. Field field = (Field) os[0];
  480. Excel excel = (Excel) os[1];
  481. // 设置实体类私有属性可访问
  482. field.setAccessible(true);
  483. this.addCell(excel, row, vo, field, column++);
  484. }
  485. }
  486. }
  487. /**
  488. * 创建表格样式
  489. *
  490. * @param wb 工作薄对象
  491. * @return 样式列表
  492. */
  493. private Map<String, CellStyle> createStyles(Workbook wb)
  494. {
  495. // 写入各条记录,每条记录对应excel表中的一行
  496. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  497. CellStyle style = wb.createCellStyle();
  498. style.setAlignment(HorizontalAlignment.CENTER);
  499. style.setVerticalAlignment(VerticalAlignment.CENTER);
  500. style.setBorderRight(BorderStyle.THIN);
  501. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  502. style.setBorderLeft(BorderStyle.THIN);
  503. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  504. style.setBorderTop(BorderStyle.THIN);
  505. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  506. style.setBorderBottom(BorderStyle.THIN);
  507. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  508. Font dataFont = wb.createFont();
  509. dataFont.setFontName("Arial");
  510. dataFont.setFontHeightInPoints((short) 10);
  511. style.setFont(dataFont);
  512. styles.put("data", style);
  513. style = wb.createCellStyle();
  514. style.cloneStyleFrom(styles.get("data"));
  515. style.setAlignment(HorizontalAlignment.CENTER);
  516. style.setVerticalAlignment(VerticalAlignment.CENTER);
  517. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  518. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  519. Font headerFont = wb.createFont();
  520. headerFont.setFontName("Arial");
  521. headerFont.setFontHeightInPoints((short) 10);
  522. headerFont.setBold(true);
  523. headerFont.setColor(IndexedColors.WHITE.getIndex());
  524. style.setFont(headerFont);
  525. styles.put("header", style);
  526. style = wb.createCellStyle();
  527. style.setAlignment(HorizontalAlignment.CENTER);
  528. style.setVerticalAlignment(VerticalAlignment.CENTER);
  529. Font totalFont = wb.createFont();
  530. totalFont.setFontName("Arial");
  531. totalFont.setFontHeightInPoints((short) 10);
  532. style.setFont(totalFont);
  533. styles.put("total", style);
  534. style = wb.createCellStyle();
  535. style.cloneStyleFrom(styles.get("data"));
  536. style.setAlignment(HorizontalAlignment.LEFT);
  537. styles.put("data1", style);
  538. style = wb.createCellStyle();
  539. style.cloneStyleFrom(styles.get("data"));
  540. style.setAlignment(HorizontalAlignment.CENTER);
  541. styles.put("data2", style);
  542. style = wb.createCellStyle();
  543. style.cloneStyleFrom(styles.get("data"));
  544. style.setAlignment(HorizontalAlignment.RIGHT);
  545. styles.put("data3", style);
  546. return styles;
  547. }
  548. /**
  549. * 创建单元格
  550. */
  551. public Cell createCell(Excel attr, Row row, int column)
  552. {
  553. // 创建列
  554. Cell cell = row.createCell(column);
  555. // 写入列信息
  556. cell.setCellValue(attr.name());
  557. setDataValidation(attr, row, column);
  558. cell.setCellStyle(styles.get("header"));
  559. return cell;
  560. }
  561. /**
  562. * 设置单元格信息
  563. *
  564. * @param value 单元格值
  565. * @param attr 注解相关
  566. * @param cell 单元格信息
  567. */
  568. public void setCellVo(Object value, Excel attr, Cell cell)
  569. {
  570. if (ColumnType.STRING == attr.cellType())
  571. {
  572. cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
  573. }
  574. else if (ColumnType.NUMERIC == attr.cellType())
  575. {
  576. if (StringUtils.isNotNull(value))
  577. {
  578. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  579. }
  580. }
  581. else if (ColumnType.IMAGE == attr.cellType())
  582. {
  583. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  584. String imagePath = Convert.toStr(value);
  585. if (StringUtils.isNotEmpty(imagePath))
  586. {
  587. byte[] data = ImageUtils.getImage(imagePath);
  588. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  589. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  590. }
  591. }
  592. }
  593. /**
  594. * 获取画布
  595. */
  596. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  597. {
  598. if (sheet.getDrawingPatriarch() == null)
  599. {
  600. sheet.createDrawingPatriarch();
  601. }
  602. return sheet.getDrawingPatriarch();
  603. }
  604. /**
  605. * 获取图片类型,设置图片插入类型
  606. */
  607. public int getImageType(byte[] value)
  608. {
  609. String type = FileTypeUtils.getFileExtendName(value);
  610. if ("JPG".equalsIgnoreCase(type))
  611. {
  612. return Workbook.PICTURE_TYPE_JPEG;
  613. }
  614. else if ("PNG".equalsIgnoreCase(type))
  615. {
  616. return Workbook.PICTURE_TYPE_PNG;
  617. }
  618. return Workbook.PICTURE_TYPE_JPEG;
  619. }
  620. /**
  621. * 创建表格样式
  622. */
  623. public void setDataValidation(Excel attr, Row row, int column)
  624. {
  625. if (attr.name().indexOf("注:") >= 0)
  626. {
  627. sheet.setColumnWidth(column, 6000);
  628. }
  629. else
  630. {
  631. // 设置列宽
  632. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  633. }
  634. // 如果设置了提示信息则鼠标放上去提示.
  635. if (StringUtils.isNotEmpty(attr.prompt()))
  636. {
  637. // 这里默认设了2-101列提示.
  638. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
  639. }
  640. // 如果设置了combo属性则本列只能选择不能输入
  641. if (attr.combo().length > 0)
  642. {
  643. // 这里默认设了2-101列只能选择不能输入.
  644. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
  645. }
  646. }
  647. /**
  648. * 添加单元格
  649. */
  650. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  651. {
  652. Cell cell = null;
  653. try
  654. {
  655. // 设置行高
  656. row.setHeight(maxHeight);
  657. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  658. if (attr.isExport())
  659. {
  660. // 创建cell
  661. cell = row.createCell(column);
  662. int align = attr.align().value();
  663. cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
  664. // 用于读取对象中的属性
  665. Object value = getTargetValue(vo, field, attr);
  666. String dateFormat = attr.dateFormat();
  667. String readConverterExp = attr.readConverterExp();
  668. String separator = attr.separator();
  669. String dictType = attr.dictType();
  670. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  671. {
  672. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  673. }
  674. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  675. {
  676. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  677. }
  678. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  679. {
  680. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  681. }
  682. else if (value instanceof BigDecimal && -1 != attr.scale())
  683. {
  684. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  685. }
  686. else
  687. {
  688. // 设置列类型
  689. setCellVo(value, attr, cell);
  690. }
  691. addStatisticsData(column, Convert.toStr(value), attr);
  692. }
  693. }
  694. catch (Exception e)
  695. {
  696. log.error("导出Excel失败{}", e);
  697. }
  698. return cell;
  699. }
  700. /**
  701. * 设置 POI XSSFSheet 单元格提示
  702. *
  703. * @param sheet 表单
  704. * @param promptTitle 提示标题
  705. * @param promptContent 提示内容
  706. * @param firstRow 开始行
  707. * @param endRow 结束行
  708. * @param firstCol 开始列
  709. * @param endCol 结束列
  710. */
  711. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  712. int firstCol, int endCol)
  713. {
  714. DataValidationHelper helper = sheet.getDataValidationHelper();
  715. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  716. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  717. DataValidation dataValidation = helper.createValidation(constraint, regions);
  718. dataValidation.createPromptBox(promptTitle, promptContent);
  719. dataValidation.setShowPromptBox(true);
  720. sheet.addValidationData(dataValidation);
  721. }
  722. /**
  723. * 设置某些列的值只能输入预制的数据,显示下拉框.
  724. *
  725. * @param sheet 要设置的sheet.
  726. * @param textlist 下拉框显示的内容
  727. * @param firstRow 开始行
  728. * @param endRow 结束行
  729. * @param firstCol 开始列
  730. * @param endCol 结束列
  731. * @return 设置好的sheet.
  732. */
  733. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  734. {
  735. DataValidationHelper helper = sheet.getDataValidationHelper();
  736. // 加载下拉列表内容
  737. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  738. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  739. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  740. // 数据有效性对象
  741. DataValidation dataValidation = helper.createValidation(constraint, regions);
  742. // 处理Excel兼容性问题
  743. if (dataValidation instanceof XSSFDataValidation)
  744. {
  745. dataValidation.setSuppressDropDownArrow(true);
  746. dataValidation.setShowErrorBox(true);
  747. }
  748. else
  749. {
  750. dataValidation.setSuppressDropDownArrow(false);
  751. }
  752. sheet.addValidationData(dataValidation);
  753. }
  754. /**
  755. * 解析导出值 0=男,1=女,2=未知
  756. *
  757. * @param propertyValue 参数值
  758. * @param converterExp 翻译注解
  759. * @param separator 分隔符
  760. * @return 解析后值
  761. */
  762. public static String convertByExp(String propertyValue, String converterExp, String separator)
  763. {
  764. StringBuilder propertyString = new StringBuilder();
  765. String[] convertSource = converterExp.split(",");
  766. for (String item : convertSource)
  767. {
  768. String[] itemArray = item.split("=");
  769. if (StringUtils.containsAny(separator, propertyValue))
  770. {
  771. for (String value : propertyValue.split(separator))
  772. {
  773. if (itemArray[0].equals(value))
  774. {
  775. propertyString.append(itemArray[1] + separator);
  776. break;
  777. }
  778. }
  779. }
  780. else
  781. {
  782. if (itemArray[0].equals(propertyValue))
  783. {
  784. return itemArray[1];
  785. }
  786. }
  787. }
  788. return StringUtils.stripEnd(propertyString.toString(), separator);
  789. }
  790. /**
  791. * 反向解析值 男=0,女=1,未知=2
  792. *
  793. * @param propertyValue 参数值
  794. * @param converterExp 翻译注解
  795. * @param separator 分隔符
  796. * @return 解析后值
  797. */
  798. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  799. {
  800. StringBuilder propertyString = new StringBuilder();
  801. String[] convertSource = converterExp.split(",");
  802. for (String item : convertSource)
  803. {
  804. String[] itemArray = item.split("=");
  805. if (StringUtils.containsAny(separator, propertyValue))
  806. {
  807. for (String value : propertyValue.split(separator))
  808. {
  809. if (itemArray[1].equals(value))
  810. {
  811. propertyString.append(itemArray[0] + separator);
  812. break;
  813. }
  814. }
  815. }
  816. else
  817. {
  818. if (itemArray[1].equals(propertyValue))
  819. {
  820. return itemArray[0];
  821. }
  822. }
  823. }
  824. return StringUtils.stripEnd(propertyString.toString(), separator);
  825. }
  826. /**
  827. * 解析字典值
  828. *
  829. * @param dictValue 字典值
  830. * @param dictType 字典类型
  831. * @param separator 分隔符
  832. * @return 字典标签
  833. */
  834. public static String convertDictByExp(String dictValue, String dictType, String separator)
  835. {
  836. return DictUtils.getDictLabel(dictType, dictValue, separator);
  837. }
  838. /**
  839. * 反向解析值字典值
  840. *
  841. * @param dictLabel 字典标签
  842. * @param dictType 字典类型
  843. * @param separator 分隔符
  844. * @return 字典值
  845. */
  846. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  847. {
  848. return DictUtils.getDictValue(dictType, dictLabel, separator);
  849. }
  850. /**
  851. * 合计统计信息
  852. */
  853. private void addStatisticsData(Integer index, String text, Excel entity)
  854. {
  855. if (entity != null && entity.isStatistics())
  856. {
  857. Double temp = 0D;
  858. if (!statistics.containsKey(index))
  859. {
  860. statistics.put(index, temp);
  861. }
  862. try
  863. {
  864. temp = Double.valueOf(text);
  865. }
  866. catch (NumberFormatException e)
  867. {
  868. }
  869. statistics.put(index, statistics.get(index) + temp);
  870. }
  871. }
  872. /**
  873. * 创建统计行
  874. */
  875. public void addStatisticsRow()
  876. {
  877. if (statistics.size() > 0)
  878. {
  879. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  880. Set<Integer> keys = statistics.keySet();
  881. Cell cell = row.createCell(0);
  882. cell.setCellStyle(styles.get("total"));
  883. cell.setCellValue("合计");
  884. for (Integer key : keys)
  885. {
  886. cell = row.createCell(key);
  887. cell.setCellStyle(styles.get("total"));
  888. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  889. }
  890. statistics.clear();
  891. }
  892. }
  893. /**
  894. * 编码文件名
  895. */
  896. public String encodingFilename(String filename)
  897. {
  898. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  899. return filename;
  900. }
  901. /**
  902. * 获取下载路径
  903. *
  904. * @param filename 文件名称
  905. */
  906. public String getAbsoluteFile(String filename)
  907. {
  908. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  909. File desc = new File(downloadPath);
  910. if (!desc.getParentFile().exists())
  911. {
  912. desc.getParentFile().mkdirs();
  913. }
  914. return downloadPath;
  915. }
  916. /**
  917. * 获取bean中的属性值
  918. *
  919. * @param vo 实体对象
  920. * @param field 字段
  921. * @param excel 注解
  922. * @return 最终的属性值
  923. * @throws Exception
  924. */
  925. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  926. {
  927. Object o = field.get(vo);
  928. if (StringUtils.isNotEmpty(excel.targetAttr()))
  929. {
  930. String target = excel.targetAttr();
  931. if (target.indexOf(".") > -1)
  932. {
  933. String[] targets = target.split("[.]");
  934. for (String name : targets)
  935. {
  936. o = getValue(o, name);
  937. }
  938. }
  939. else
  940. {
  941. o = getValue(o, target);
  942. }
  943. }
  944. return o;
  945. }
  946. /**
  947. * 以类的属性的get方法方法形式获取值
  948. *
  949. * @param o
  950. * @param name
  951. * @return value
  952. * @throws Exception
  953. */
  954. private Object getValue(Object o, String name) throws Exception
  955. {
  956. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  957. {
  958. Class<?> clazz = o.getClass();
  959. Field field = clazz.getDeclaredField(name);
  960. field.setAccessible(true);
  961. o = field.get(o);
  962. }
  963. return o;
  964. }
  965. /**
  966. * 得到所有定义字段
  967. */
  968. private void createExcelField()
  969. {
  970. this.fields = new ArrayList<Object[]>();
  971. List<Field> tempFields = new ArrayList<>();
  972. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  973. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  974. for (Field field : tempFields)
  975. {
  976. // 单注解
  977. if (field.isAnnotationPresent(Excel.class))
  978. {
  979. putToField(field, field.getAnnotation(Excel.class));
  980. }
  981. // 多注解
  982. if (field.isAnnotationPresent(Excels.class))
  983. {
  984. Excels attrs = field.getAnnotation(Excels.class);
  985. Excel[] excels = attrs.value();
  986. for (Excel excel : excels)
  987. {
  988. putToField(field, excel);
  989. }
  990. }
  991. }
  992. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  993. this.maxHeight = getRowHeight();
  994. }
  995. /**
  996. * 根据注解获取最大行高
  997. */
  998. public short getRowHeight()
  999. {
  1000. double maxHeight = 0;
  1001. for (Object[] os : this.fields)
  1002. {
  1003. Excel excel = (Excel) os[1];
  1004. maxHeight = maxHeight > excel.height() ? maxHeight : excel.height();
  1005. }
  1006. return (short) (maxHeight * 20);
  1007. }
  1008. /**
  1009. * 放到字段集合中
  1010. */
  1011. private void putToField(Field field, Excel attr)
  1012. {
  1013. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1014. {
  1015. this.fields.add(new Object[] { field, attr });
  1016. }
  1017. }
  1018. /**
  1019. * 创建一个工作簿
  1020. */
  1021. public void createWorkbook()
  1022. {
  1023. this.wb = new SXSSFWorkbook(500);
  1024. }
  1025. /**
  1026. * 创建工作表
  1027. *
  1028. * @param sheetNo sheet数量
  1029. * @param index 序号
  1030. */
  1031. public void createSheet(double sheetNo, int index)
  1032. {
  1033. this.sheet = wb.createSheet();
  1034. this.styles = createStyles(wb);
  1035. // 设置工作表的名称.
  1036. if (sheetNo == 0)
  1037. {
  1038. wb.setSheetName(index, sheetName);
  1039. }
  1040. else
  1041. {
  1042. wb.setSheetName(index, sheetName + index);
  1043. }
  1044. }
  1045. /**
  1046. * 获取单元格值
  1047. *
  1048. * @param row 获取的行
  1049. * @param column 获取单元格列号
  1050. * @return 单元格值
  1051. */
  1052. public Object getCellValue(Row row, int column)
  1053. {
  1054. if (row == null)
  1055. {
  1056. return row;
  1057. }
  1058. Object val = "";
  1059. try
  1060. {
  1061. Cell cell = row.getCell(column);
  1062. if (StringUtils.isNotNull(cell))
  1063. {
  1064. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1065. {
  1066. val = cell.getNumericCellValue();
  1067. if (DateUtil.isCellDateFormatted(cell))
  1068. {
  1069. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1070. }
  1071. else
  1072. {
  1073. if ((Double) val % 1 != 0)
  1074. {
  1075. val = new BigDecimal(val.toString());
  1076. }
  1077. else
  1078. {
  1079. val = new DecimalFormat("0").format(val);
  1080. }
  1081. }
  1082. }
  1083. else if (cell.getCellType() == CellType.STRING)
  1084. {
  1085. val = cell.getStringCellValue();
  1086. }
  1087. else if (cell.getCellType() == CellType.BOOLEAN)
  1088. {
  1089. val = cell.getBooleanCellValue();
  1090. }
  1091. else if (cell.getCellType() == CellType.ERROR)
  1092. {
  1093. val = cell.getErrorCellValue();
  1094. }
  1095. }
  1096. }
  1097. catch (Exception e)
  1098. {
  1099. return val;
  1100. }
  1101. return val;
  1102. }
  1103. /**
  1104. * 判断是否是空行
  1105. *
  1106. * @param row 判断的行
  1107. * @return
  1108. */
  1109. private boolean isRowEmpty(Row row)
  1110. {
  1111. if (row == null)
  1112. {
  1113. return true;
  1114. }
  1115. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1116. {
  1117. Cell cell = row.getCell(i);
  1118. if (cell != null && cell.getCellType() != CellType.BLANK)
  1119. {
  1120. return false;
  1121. }
  1122. }
  1123. return true;
  1124. }
  1125. /**
  1126. * 获取Excel2003图片
  1127. *
  1128. * @param sheet 当前sheet对象
  1129. * @param workbook 工作簿对象
  1130. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1131. */
  1132. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1133. {
  1134. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1135. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1136. if (!pictures.isEmpty())
  1137. {
  1138. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1139. {
  1140. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1141. if (shape instanceof HSSFPicture)
  1142. {
  1143. HSSFPicture pic = (HSSFPicture) shape;
  1144. int pictureIndex = pic.getPictureIndex() - 1;
  1145. HSSFPictureData picData = pictures.get(pictureIndex);
  1146. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
  1147. sheetIndexPicMap.put(picIndex, picData);
  1148. }
  1149. }
  1150. return sheetIndexPicMap;
  1151. }
  1152. else
  1153. {
  1154. return sheetIndexPicMap;
  1155. }
  1156. }
  1157. /**
  1158. * 获取Excel2007图片
  1159. *
  1160. * @param sheet 当前sheet对象
  1161. * @param workbook 工作簿对象
  1162. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1163. */
  1164. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1165. {
  1166. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1167. for (POIXMLDocumentPart dr : sheet.getRelations())
  1168. {
  1169. if (dr instanceof XSSFDrawing)
  1170. {
  1171. XSSFDrawing drawing = (XSSFDrawing) dr;
  1172. List<XSSFShape> shapes = drawing.getShapes();
  1173. for (XSSFShape shape : shapes)
  1174. {
  1175. if (shape instanceof XSSFPicture)
  1176. {
  1177. XSSFPicture pic = (XSSFPicture) shape;
  1178. XSSFClientAnchor anchor = pic.getPreferredSize();
  1179. CTMarker ctMarker = anchor.getFrom();
  1180. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1181. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1182. }
  1183. }
  1184. }
  1185. }
  1186. return sheetIndexPicMap;
  1187. }
  1188. }