一行代码导出excel —— EasyExcel的实践

对excel的操作,一般常用的是poi,对excel可以进行操作导入导出,但是poi使用起来有些繁琐,并且不易理解,开源新工具 easyexcel,简单的配置+一键导出,简单粗暴,该组件的简介是:快速、简单避免OOM的java处理Excel工具

一、添加依赖

	<dependency>
		<groupId>cn.afterturngroupId>
		<artifactId>easypoi-baseartifactId>
		<version>3.0.3version>
	dependency>
	<dependency>
		<groupId>cn.afterturngroupId>
		<artifactId>easypoi-webartifactId>
		<version>3.0.3version> dependency>
	<dependency>
		<groupId>cn.afterturngroupId>
		<artifactId>easypoi-annotationartifactId>
		<version>3.0.3version>
	dependency>

二、工具类

其实,也不需要工具类,完全可以直接使用easyexcle中提供的工具类完成导出,这里提供的工具类是根据需要又做了一层封装,如果简单的导出,可以直接使用过easyexcle中的api

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;


public class EasyExcelUtil {

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
                                   String fileName, boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * 导出excel文件,格式为xlsx
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,
                                   HttpServletResponse response){
        // 如果是xls文件,则设置ExcelType.HSSF 或者不设置, xlsx文件需设置ExcelType.XSSF
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }

    /**
     * 导出excel文件,格式为.xls
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @param response
     */
    public static void exportExcelWithXls(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,
                                   HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
                                      HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = cn.afterturn.easypoi.excel.ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null); downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = cn.afterturn.easypoi.excel.ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new RuntimeException("模板不能为空");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){ return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
             throw new RuntimeException("excel文件不能为空");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;
    }

}

三、创建excel对应实体类

实体类中的属性,可以通过注解的方式指定对应的列名和该单元格的值

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Excel导出实体
 */
@Data
@NoArgsConstructor
public class PromotionExcelResponseVO {

	/**
     * excel注解中有其他的属性,可以用来设置宽高、格式化、合并单元格等
     *
     *	name 指定生成excel的列名
     *  orderNum 指定该属性对应的第几列
     *  width 指定该列的宽度
     *  height 指定该列的高度
     *  type 设置导出的类型,1:文本 2:图片 3:函数 10:数字
     */
    @Excel(name = "大区" ,orderNum = "0", width=50, height = 30, type=1)
    private String area;

    @Excel(name = "城市" ,orderNum = "1")
    private String city;

    @Excel(name = "物料尺寸" ,orderNum = "2")
    private String originSize;

    @Excel(name = "可视尺寸" ,orderNum = "3")
    private String clearSize;

    @Excel(name = "姓名", orderNum = "4")
    private String name;

    @Excel(name = "地址", orderNum = "5")
    private String address;

    @Excel(name = "电话", orderNum = "6")
    private String mobile;
		
  	/**
     * 表示该属性不会导出
     */
    @ExcelIgnore
    private String model;
		
  	/**
     * 导出的数据为百分比格式
     */
    @Excel(name = "通用优惠", orderNum = "8", numFormat = "#.##%")
    private BigDecimal promotionDetail;
		
  	/**
     * 导出的数据后面为小数 xx.00
     */
    @Excel(name = "促销价格", orderNum = "9", numFormat = "0.00")
    private String otherPromotionDetail;
		
	// 没有注解的属性,则不会导出到excel中
    private String projectName;

}

四、导出excel

只需要将查询出来的数据,转换为对应的excel实体类,通过easyexcel的工具类即可导出

@RequestMapping(value = "exportExcel")
public void exportExcel(HttpServletResponse response, 								@RequestParam("projectName") String projectName) {
        List<PromotionInfo> list = promotionService.findAllByProjectName(projectName);
        List<PromotionExcelResponseVO> list1 = list.stream().map(item -> {
            PromotionExcelResponseVO vo = new PromotionExcelResponseVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
        EasyExcelUtil.exportExcel(list1, projectName, "sheet1", PromotionExcelResponseVO.class, "导出数据.xlsx", response);
}

五、easyexcel注解详解

关于easyexcel中注解及属性说明

@Excel 作用到filed上面,是对Excel一列的一个描述

@ExcelCollection 表示一个集合,主要针对一对多的导出,

@ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理

@ExcelIgnore 忽略该字段导出到excel

  • @Excel
    一行代码导出excel —— EasyExcel的实践_第1张图片

  • @ExcelTarget
    一行代码导出excel —— EasyExcel的实践_第2张图片

  • @ExcelCollection
    一行代码导出excel —— EasyExcel的实践_第3张图片

你可能感兴趣的:(Java)