ExcelUtil.java 43 KB

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