EasyExcel实现excel导入导出快速开发,如同其名 easy easy

EasyExcel

Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出。
阿里开源,github:https://github.com/alibaba/easyexcel

使用(有模型)

1. 引包


	com.alibaba
    easyexcel
    1.1.2-beta5
  

 
    org.apache.poi
     poi
     4.0.0
 
 
     org.apache.poi
     poi-ooxml
     4.0.0
 
 
     cglib
     cglib
     3.3.0
 

2. 定义模型

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelEmployee extends BaseRowModel{

 	@ExcelProperty(value = {"员工信息","序号"} ,index = 0)
    private String sortNo;

    @ExcelProperty(value = {"员工信息","员工代码","EMPCODE"},index = 1)
    private String employeeCode;

    @ExcelProperty(value = {"员工信息","用户登录名","USERNAME"},index = 2)
    private String userName;
    
    @ExcelProperty(value = {"员工信息","员工姓名","EMPNAME"},index = 3)
    private String trueName;
	。。。。。。。。。。。。。
}

3. 自定义工具类(有模型写、有模型读、自定义参数类)

@Component
public class ExcelUtil {

	private static StyleExcelHandler styleExcelHandler;
 
	@Autowired
    public void setStyleExcelHandler(StyleExcelHandler styleExcelHandler){
		ExcelUtil.styleExcelHandler = styleExcelHandler;
    }
	
	
	  /**
	   * @param inputStream 输入流
	   * @param sheetNo     工作表编号
	   * @param headLineMun 标题占用行数
	   */
	public static List readJavaModel(InputStream inputStream, ExcelParameter excelParam, Class clazz) {
	      List data = null;
	      try {
	          data = EasyExcelFactory.read(inputStream, new Sheet(excelParam.getSheetNo(), excelParam.getHeadLineMun(), clazz));
	          inputStream.close();
	      } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          try {
	              inputStream.close();
	          } catch (IOException e) {
	              e.printStackTrace();
	          }
	      }	 
	      return data;
	  }
	  
    /**
     * 写Excel文件
     *
     * @param excelTypeEnum excel版本
     * @param fileName      包含文件路径的文件名
     * @param sheetName     sheet名
     * @param datas         文件数据(包含表头)
     */
	public static void writeExcel(OutputStream outputStream, List excelParameterList,
			List> employeeDateList) {
	 
		
		 try {         
			 ExcelWriter writer = new ExcelWriter(null, outputStream, ExcelTypeEnum.XLSX, true, styleExcelHandler);			  
			// ExcelWriter writer = EasyExcelFactory.getWriter(outputStream);			 
			 for (int j = 0; j < excelParameterList.size(); j++) {
				 ExcelParameter parameter = excelParameterList.get(j);
				 List data = employeeDateList.get(j);
				 Class t;
	 	         if (data != null && data.size() > 0) {
	 	            t = data.get(0).getClass();
	 	         } else {
	 	           continue;
	 	         }
	 	         
	 	        Sheet sheet = new Sheet(parameter.sheetNo, parameter.headLineMun, t, parameter.sheetName, null);
	 	        sheet.setStartRow(parameter.getStartRow());
	 	         
	 	        //设置列宽 设置每列的宽度
	 	        if (parameter.columnWidth != null && parameter.columnWidth.size() > 0) {
	 	            sheet.setColumnWidthMap(parameter.columnWidth);	 	            
	 	        } else {
	 	            // 设置自适应宽度
	 	            sheet.setAutoWidth(Boolean.TRUE);
	 	        }
	 	       
	 	        writer.write(data, sheet);
	 	        //合并单元格
	 	        if (parameter.getMergeParameterList() != null && parameter.getMergeParameterList().size() > 0) {
	 	            for (MergeParameter mergeParameter : parameter.getMergeParameterList()) {
	 	                writer.merge(mergeParameter.firstRow, mergeParameter.lastRow, mergeParameter.firstCol, mergeParameter.lastCol);
	 	            }
	 	        } 	       
			}
			 writer.finish();
		 } catch (RuntimeException e) {
	 	        e.printStackTrace();
	 	    } finally {
	 	        try {
	 	            outputStream.close();
	 	        } catch (IOException e) {
	 	            e.printStackTrace();
	 	        }
	 	    }
	}
	
	@Data
    public static class ExcelParameter {
        /**
         * 工作表编号
         */
        private Integer sheetNo;
        /**
         * 标题占用行数
         */
        private Integer headLineMun;
        /**
         * 工作表名称
         */
        private String sheetName;
        /**
         * 表头
         */
        private List> listStringHead;
        /**
         * 宽度
         */
        private Map columnWidth;
        /**
         * 开始行号
         */
        private Integer startRow;
        
        /**
         * 合并单元格参数
         */
        private List mergeParameterList;
    }

    /**
     * 单元格合并参数
     */
    @Data
    @AllArgsConstructor
	public  static class MergeParameter {
        /**
         * 起始行
         */
        private Integer firstRow;
        /**
         * 结束行
         */
        private Integer lastRow;
        /**
         * 起始列
         */
        private Integer firstCol;
        /**
         * 结束列
         */
        private Integer lastCol;
    }
}
 
  

4. 实现WriteHandler,自定义单元格样式

@Component
public class StyleExcelHandler  implements WriteHandler {

    @Override
    public void sheet(int i, Sheet sheet) {
    }
    @Override
    public void row(int i, Row row) {
    }
    @Override
    public void cell(int i, Cell cell) {  
    	Sheet sheet = cell.getSheet();
        Workbook workbook = sheet.getWorkbook();
        CellStyle cellStyle = createStyle(workbook);
        
        Font font = workbook.createFont();
        font.setFontName("黑体");  
        String sheetName = sheet.getSheetName();
        if(sheetName.equals("员工信息")) {
        	 if(cell.getRowIndex() <= 2) {
            	 if (i == 5) {
                     cellStyle.setFillPattern(FillPatternType.LESS_DOTS);//设置前景填充样式
                     cellStyle.setFillBackgroundColor((short)13);
                     cellStyle.setFillForegroundColor((short)13);
                 }            	
            	 font.setFontHeightInPoints((short) 12); 
        	}else{
        		  font.setFontHeightInPoints((short) 8); 
        	}
        }else {
        	 if(cell.getRowIndex() < 1) {
        		 font.setFontHeightInPoints((short) 12); 
        	 }else {
        		 font.setFontHeightInPoints((short) 8);
        	 }
        }
       
        cellStyle.setFont(font);
        
        cell.getRow().getCell(i).setCellStyle(cellStyle);
    }
    /**
      * 实际中如果直接获取原单元格的样式进行修改, 最后发现是改了整行的样式, 因此这里是新建一个样* 式
      */
    private CellStyle createStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        // 下边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        // 左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        // 上边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        // 右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        // 水平对齐方式
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 垂直对齐方式
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }
}

5. 测试


	public static void main(String[] args) throws FileNotFoundException {
		List excelParameterList = new ArrayList<>();
    	ExcelParameter excelParam1 =  new ExcelParameter();
    	excelParam1.setSheetNo(1);
    	excelParam1.setHeadLineMun(2);
    	excelParam1.setSheetName("员工信息");
    	excelParam1.setStartRow(0);
    	MergeParameter m1 = new MergeParameter(1,2,0,0);
    	List mergeParameterList1 = new ArrayList<>();
    	mergeParameterList1.add(m1);
    	 
    	excelParam1.setMergeParameterList(mergeParameterList1);
    	
    	Map columnWidth = new HashMap<>();
    	columnWidth.put(0, 2000);
    	columnWidth.put(1, 3000);
    	columnWidth.put(2, 4000);
    	columnWidth.put(3, 3000);
    	
    	excelParam1.setColumnWidth(columnWidth);
    	excelParameterList.add(excelParam1);
    	
    	OutputStream outputStream = new FileOutputStream(new File("E:\\test.xlsx"));
    	List> employeeDate = new ArrayList<>();
    	employeeDate.add(Arrays.asList(new ExcelEmployee()));
    	
    	writeExcel(outputStream, excelParameterList, employeeDate);
     
	}

在这里插入图片描述

你可能感兴趣的:(码农进阶)