ExcelUtils.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package org.jeecg.modules.excelutil;
  2. import com.alibaba.excel.EasyExcelFactory;
  3. import com.alibaba.excel.ExcelReader;
  4. import com.alibaba.excel.ExcelWriter;
  5. import com.alibaba.excel.event.AnalysisEventListener;
  6. import com.alibaba.excel.metadata.BaseRowModel;
  7. import com.alibaba.excel.metadata.Sheet;
  8. import com.alibaba.excel.support.ExcelTypeEnum;
  9. import java.io.*;
  10. import java.util.List;
  11. public class ExcelUtils {
  12. /**
  13. * @param is 导入文件输入流
  14. * @param clazz Excel实体映射类
  15. * @return
  16. */
  17. public static Boolean readExcel(InputStream is, Class clazz, AnalysisEventListener listener) {
  18. BufferedInputStream bis = null;
  19. try {
  20. bis = new BufferedInputStream(is);
  21. // 解析每行结果在listener中处理
  22. ExcelReader excelReader = EasyExcelFactory.getReader(bis, listener);
  23. excelReader.read(new Sheet(1, 1, clazz));
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. return false;
  27. } finally {
  28. if (bis != null) {
  29. try {
  30. bis.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  36. return true;
  37. }
  38. /**
  39. * @param os 文件输出流
  40. * @param clazz Excel实体映射类
  41. * @param data 导出数据
  42. * @return
  43. */
  44. public static Boolean writeExcel(OutputStream os, Class clazz, List<? extends BaseRowModel> data) {
  45. BufferedOutputStream bos = null;
  46. try {
  47. bos = new BufferedOutputStream(os);
  48. ExcelWriter writer = new ExcelWriter(bos, ExcelTypeEnum.XLSX);
  49. //写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
  50. Sheet sheet1 = new Sheet(1, 0, clazz);
  51. writer.write(data, sheet1);
  52. writer.finish();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. return false;
  56. } finally {
  57. if (bos != null) {
  58. try {
  59. bos.close();
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65. return true;
  66. }
  67. }