1.什么是easyExcel

2.如何使用

1.引入pom包

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>easyexcel</artifactId>
  4. <version>1.1.2-beat1</version>
  5. </dependency>

3.导入使用

1.定义实体类

  1. @ExcelProperty(index = 0 , value = "时间")
  2. private String TIME;
  3. @ExcelProperty(index = 1 , value = "开盘")
  4. private String OPENING;
  5. @ExcelProperty(index = 2 , value = "最高")
  6. private String MAXHIGH;
  7. @ExcelProperty(index = 3 , value = "最低")
  8. private String MINLOWEST;
  9. @ExcelProperty(index = 4 , value = "收盘")
  10. private String CLOSE_PAN;
  11. @ExcelProperty(index = 5 , value = "成交量")
  12. private String VOLUME;
  13. @ExcelProperty(index = 6 , value = "股票代码")
  14. private String STOCK_SYMBOL;
  15. //@ExcelProperty(index = 0 , value = "时间")
  16. //index:表示第几列
  17. //value:表示这一列对于的名字

2.添加导入数据监听类

  1. /**
  2. * 监听类,可以自定义
  3. *
  4. * @author liuyi
  5. * @Created 2019-7-18 18:01:53
  6. **/
  7. public class ExcelListener extends AnalysisEventListener {
  8. /**
  9. * 自定义用于暂时存储data。
  10. * 可以通过实例获取该值
  11. */
  12. private List<Object> datas = new ArrayList<>();
  13. /**
  14. * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据
  15. */
  16. @Override
  17. public void invoke(Object object, AnalysisContext context) {
  18. //数据存储到list,供批量处理,或后续自己业务逻辑处理。
  19. datas.add(object);
  20. //根据业务自行 do something
  21. doSomething();
  22. /*
  23. 如数据过大,可以进行定量分批处理
  24. if(datas.size()<=100){
  25. datas.add(object);
  26. }else {
  27. doSomething();
  28. datas = new ArrayList<Object>();
  29. }
  30. */
  31. }
  32. /**
  33. * 根据业务自行实现该方法
  34. */
  35. private void doSomething() {
  36. }
  37. @Override
  38. public void doAfterAllAnalysed(AnalysisContext context) {
  39. /*
  40. datas.clear();
  41. 解析结束销毁不用的资源
  42. */
  43. }
  44. public List<Object> getDatas() {
  45. return datas;
  46. }
  47. public void setDatas(List<Object> datas) {
  48. this.datas = datas;
  49. }
  50. }

3.编写导入导出工具类

  1. /**
  2. * Excel工具类
  3. *
  4. * @author liuyi
  5. * @Created 2019-7-18 18:01:53
  6. **/
  7. public class ExcelUtil {
  8. /**
  9. * 读取 Excel(多个 sheet)
  10. *
  11. * @param excel 文件
  12. * @param rowModel 实体类映射,继承 BaseRowModel 类
  13. * @return Excel 数据 list
  14. */
  15. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) throws ExcelException {
  16. ExcelListener excelListener = new ExcelListener();
  17. ExcelReader reader = getReader(excel, excelListener);
  18. if (reader == null) {
  19. return null;
  20. }
  21. for (Sheet sheet : reader.getSheets()) {
  22. if (rowModel != null) {
  23. sheet.setClazz(rowModel.getClass());
  24. }
  25. reader.read(sheet);
  26. }
  27. return excelListener.getDatas();
  28. }
  29. /**
  30. * 读取某个 sheet 的 Excel
  31. *
  32. * @param excel 文件
  33. * @param rowModel 实体类映射,继承 BaseRowModel 类
  34. * @param sheetNo sheet 的序号 从1开始
  35. * @return Excel 数据 list
  36. */
  37. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) throws ExcelException {
  38. return readExcel(excel, rowModel, sheetNo, 1);
  39. }
  40. /**
  41. * 读取某个 sheet 的 Excel
  42. *
  43. * @param excel 文件
  44. * @param rowModel 实体类映射,继承 BaseRowModel 类
  45. * @param sheetNo sheet 的序号 从1开始
  46. * @param headLineNum 表头行数,默认为1
  47. * @return Excel 数据 list
  48. */
  49. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) throws ExcelException {
  50. ExcelListener excelListener = new ExcelListener();
  51. ExcelReader reader = getReader(excel, excelListener);
  52. if (reader == null) {
  53. return null;
  54. }
  55. reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
  56. return excelListener.getDatas();
  57. }
  58. /**
  59. * 导出 Excel :一个 sheet,带表头
  60. *
  61. * @param response HttpServletResponse
  62. * @param list 数据 list,每个元素为一个 BaseRowModel
  63. * @param fileName 导出的文件名
  64. * @param sheetName 导入文件的 sheet 名
  65. * @param object 映射实体类,Excel 模型
  66. */
  67. public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list, String fileName,
  68. String sheetName, BaseRowModel object) throws ExcelException {
  69. ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
  70. Sheet sheet = new Sheet(1, 0, object.getClass());
  71. sheet.setSheetName(sheetName);
  72. TableStyle tableStyle = new TableStyle();
  73. tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
  74. Font font = new Font();
  75. font.setFontHeightInPoints((short) 9);
  76. tableStyle.setTableHeadFont(font);
  77. tableStyle.setTableContentFont(font);
  78. sheet.setTableStyle(tableStyle);
  79. writer.write(list, sheet);
  80. writer.finish();
  81. }
  82. /**
  83. * 导出 Excel :多个 sheet,带表头
  84. *
  85. * @param response HttpServletResponse
  86. * @param list 数据 list,每个元素为一个 BaseRowModel
  87. * @param fileName 导出的文件名
  88. * @param sheetName 导入文件的 sheet 名
  89. * @param object 映射实体类,Excel 模型
  90. */
  91. public static ExcelWriterFactory writeExcelWithSheets(HttpServletResponse response,
  92. List<? extends BaseRowModel> list, String fileName,
  93. String sheetName, BaseRowModel object) throws ExcelException {
  94. ExcelWriterFactory writer = new ExcelWriterFactory(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
  95. Sheet sheet = new Sheet(1, 0, object.getClass());
  96. sheet.setSheetName(sheetName);
  97. sheet.setTableStyle(getTableStyle());
  98. writer.write(list, sheet);
  99. return writer;
  100. }
  101. /**
  102. * 导出融资还款情况表
  103. *
  104. * @param response
  105. * @param list
  106. * @param fileName
  107. * @param sheetName
  108. * @param object
  109. */
  110. public static void writeFinanceRepayment(HttpServletResponse response, List<? extends BaseRowModel> list,
  111. String fileName, String sheetName, BaseRowModel object) throws ExcelException {
  112. ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
  113. Sheet sheet = new Sheet(1, 0, object.getClass());
  114. sheet.setSheetName(sheetName);
  115. sheet.setTableStyle(getTableStyle());
  116. writer.write(list, sheet);
  117. for (int i = 1; i <= list.size(); i += 4) {
  118. writer.merge(i, i + 3, 0, 0);
  119. writer.merge(i, i + 3, 1, 1);
  120. }
  121. writer.finish();
  122. }
  123. /**
  124. * 导出文件时为Writer生成OutputStream
  125. */
  126. private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws ExcelException {
  127. //创建本地文件
  128. fileName = fileName + ".xls";
  129. try {
  130. fileName = new String(fileName.getBytes(), "ISO-8859-1");
  131. response.addHeader("Content-Disposition", "filename=" + fileName);
  132. return response.getOutputStream();
  133. } catch (Exception e) {
  134. throw new ExcelException("导出异常!");
  135. }
  136. }
  137. /**
  138. * 返回 ExcelReader
  139. *
  140. * @param excel 需要解析的 Excel 文件
  141. * @param excelListener new ExcelListener()
  142. */
  143. private static ExcelReader getReader(MultipartFile excel, ExcelListener excelListener) throws ExcelException {
  144. String filename = excel.getOriginalFilename();
  145. if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
  146. throw new ExcelException("文件格式错误!");
  147. }
  148. InputStream inputStream;
  149. try {
  150. inputStream = new BufferedInputStream(excel.getInputStream());
  151. return new ExcelReader(inputStream, null, excelListener, false);
  152. } catch (IOException e) {
  153. e.printStackTrace();
  154. }
  155. return null;
  156. }
  157. /**
  158. * 资金收支导出 Excel :一个 sheet,带表头
  159. *
  160. * @param response HttpServletResponse
  161. * @param list 数据 list,每个元素为一个 BaseRowModel
  162. * @param fileName 导出的文件名
  163. * @param sheetName 导入文件的 sheet 名
  164. * @param object 映射实体类,Excel 模型
  165. */
  166. public static void exportFundBudgetExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
  167. String fileName, String sheetName, BaseRowModel object) throws IOException, ExcelException {
  168. ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
  169. Sheet sheet = new Sheet(1, 0, object.getClass());
  170. sheet.setSheetName(sheetName);
  171. sheet.setTableStyle(getTableStyle());
  172. writer.write(list, sheet);
  173. writer.merge(2, 3, 0, 0);
  174. writer.merge(4, 13, 0, 0);
  175. writer.merge(14, 14, 0, 1);
  176. writer.finish();
  177. }
  178. /**
  179. * 读取Excel表格数据,封装成实体
  180. *
  181. * @param inputStream
  182. * @param clazz
  183. * @param sheetNo
  184. * @param headLineMun
  185. * @return
  186. */
  187. public static Object readExcel(InputStream inputStream, Class<? extends BaseRowModel> clazz, Integer sheetNo,
  188. Integer headLineMun) throws ExcelException {
  189. if (null == inputStream) {
  190. throw new NullPointerException("the inputStream is null!");
  191. }
  192. ExcelListener listener = new ExcelListener();
  193. ExcelReader reader = new ExcelReader(inputStream, valueOf(inputStream), null, listener);
  194. reader.read(new Sheet(sheetNo, headLineMun, clazz));
  195. return listener.getDatas();
  196. }
  197. /**
  198. * 根据输入流,判断为xls还是xlsx,该方法原本存在于easyexcel 1.1.0 的ExcelTypeEnum中。
  199. */
  200. public static ExcelTypeEnum valueOf(InputStream inputStream) throws ExcelException {
  201. try {
  202. FileMagic fileMagic = FileMagic.valueOf(inputStream);
  203. if (FileMagic.OLE2.equals(fileMagic)) {
  204. return ExcelTypeEnum.XLS;
  205. }
  206. if (FileMagic.OOXML.equals(fileMagic)) {
  207. return ExcelTypeEnum.XLSX;
  208. }
  209. throw new ExcelException("excelTypeEnum can not null");
  210. } catch (IOException e) {
  211. throw new RuntimeException(e);
  212. }
  213. // return null;
  214. }
  215. /**
  216. * 设置全局样式
  217. *
  218. * @return
  219. */
  220. private static TableStyle getTableStyle() {
  221. TableStyle tableStyle = new TableStyle();
  222. tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
  223. Font font = new Font();
  224. font.setBold(true);
  225. font.setFontHeightInPoints((short) 9);
  226. tableStyle.setTableHeadFont(font);
  227. Font fontContent = new Font();
  228. fontContent.setFontHeightInPoints((short) 9);
  229. tableStyle.setTableContentFont(fontContent);
  230. return tableStyle;
  231. }
  232. }

4.编写异常扩展类

  1. public class ExcelException extends Exception {
  2. public ExcelException() {
  3. // TODO Auto-generated constructor stub
  4. }
  5. public ExcelException(String message) {
  6. super(message);
  7. // TODO Auto-generated constructor stub
  8. }
  9. public ExcelException(Throwable cause) {
  10. super(cause);
  11. // TODO Auto-generated constructor stub
  12. }
  13. public ExcelException(String message, Throwable cause) {
  14. super(message, cause);
  15. // TODO Auto-generated constructor stub
  16. }
  17. }

5.调用方法

  1. // excel:MultipartFile
  2. // ExcelEntity:对应的实体类
  3. // d调用导入方法后吧objLiest强转为List<ExcelEntity> ,此对象存储了所有的数据
  4. Object objList = readExcel(excel, new ExcelEntity(),3);
  5. List<ExcelEntity> orderList = (List<ExcelEntity>) objList;

4.easyExcel导出字典值的映射转换

主要通过制定converter来实现
image.png

  1. /**
  2. * easyexcel关于导出的字典值转换
  3. */
  4. public class ExcelDictConverter implements Converter {
  5. private String[] dictCodIsYesNoArr ={"afterSalesStatus", ""};
  6. /**
  7. * 返回Java中的对象类型
  8. * @return Support for Java class
  9. */
  10. @Override
  11. public Class supportJavaTypeKey() {
  12. return Integer.class;
  13. }
  14. /**
  15. * 返回excel中的对象枚举
  16. * @return Support for {@link CellDataTypeEnum}
  17. */
  18. @Override
  19. public CellDataTypeEnum supportExcelTypeKey() {
  20. return CellDataTypeEnum.STRING;
  21. }
  22. /**
  23. * 将Excel对象转换为Java对象
  24. * @param cellData Excel单元格数据。
  25. * @param contentProperty 内容属性。可为空。
  26. * @param globalConfiguration 全局配置。
  27. * @return 放入Java对象的数据
  28. * @throws Exception Exception.
  29. */
  30. @Override
  31. public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  32. // 1、获取解析的某个excel字符内容
  33. // String value = cellData.getStringValue();
  34. //return DataTranferEnum.getValue(value);
  35. return null;
  36. }
  37. /**
  38. * 将Java对象转换为Excel对象
  39. * @param value Java Data.NotNull。
  40. * @param contentProperty 内容属性。可为空。
  41. * @param globalConfiguration 全局配置。
  42. * @return 数据放入Excel
  43. * @throws Exception Exception.
  44. */
  45. @Override
  46. public CellData convertToExcelData(Integer dictKey, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  47. // 1、获取属性名
  48. // String attributeName = contentProperty.getField().getName();
  49. // 2、通过属性名和java属性值获取对应的Excel字符值
  50. // String excelValue = DataTranferEnum.getExcelValueByProperName(attributeName,value); DataTranferEnum 自定义类
  51. // if(StringUtils.isNotBlank(excelValue)){
  52. // return new CellData(excelValue);
  53. // }
  54. // return new CellData(value);
  55. // 类里需要转换的字段
  56. Field field = excelContentProperty.getField();
  57. String fieldName = field.getName();
  58. String excelValue;
  59. // 字典值为yes_no的字段
  60. if (StringUtils.equalsAnyIgnoreCase(fieldName, dictCodIsYesNoArr)) {
  61. excelValue = DictCache.getValue(DictEnum.YES_NO, dictKey);
  62. }else {
  63. // 将字段名转换成下划线连接(也就是字典表里的code
  64. String dictCode = camelToUnderline(fieldName);
  65. // 当前字段对应的字典值
  66. excelValue = DictCache.getValue(dictCode, dictKey);
  67. }
  68. return new CellData(StringUtil.isBlank(excelValue) ? dictKey.toString() : excelValue);
  69. }
  70. /**
  71. * 驼峰转成下划线
  72. *
  73. * @param sourStr 需要转换的字符串,如:orderStatus
  74. * @return 转换后的字符串,如:order_status
  75. */
  76. public String camelToUnderline(String sourStr) {
  77. if (sourStr == null || "".equals(sourStr.trim())) {
  78. return "";
  79. }
  80. int len = sourStr.length();
  81. StringBuilder sb = new StringBuilder(len);
  82. for (int i = 0; i < len; i++) {
  83. char c = sourStr.charAt(i);
  84. if (Character.isUpperCase(c)) {
  85. sb.append('_');
  86. }
  87. sb.append(Character.toLowerCase(c));
  88. }
  89. return sb.toString();
  90. }
  91. }