ExcelUtil.java 40 KB

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