Java EasyPoi使用详解

此文章基于SpringBoot框架

EasyPoi参考文档

1. Pom文件加入

		<!-- easypoi导入导出 -->
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.0.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-web</artifactId>
			<version>3.0.3</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>3.0.3</version>
		</dependency>

2. 新建EasyPoiUtil工具类

import cn.afterturn.easypoi.excel.ExcelExportUtil;
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 cn.mdsoftware.BaoXianYuYue.bean.api.HttpResponse;
import cn.mdsoftware.BaoXianYuYue.bean.entity.BookingOrderDO;
import org.apache.commons.lang.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.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

public class EasyPoiUtil
{
    /**
     * 功能描述:复杂导出Excel,包括文件名以及表名。创建表头
     *
     * @author HeJD
     * @date 2018/10/9 13:54
     * @param list 导出的实体类
     * @param title 表头名称
     * @param sheetName sheet表名
     * @param pojoClass 映射的实体类
     * @param isCreateHeader 是否创建表头
     * @param fileName
     * @param response
     * @return
     */
    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,包括文件名以及表名,不创建表头
     *
     * @author HeJD
     * @date 2018/10/9 13:54
     * @param list 导出的实体类
     * @param title 表头名称
     * @param sheetName sheet表名
     * @param pojoClass 映射的实体类
     * @param fileName
     * @param response
     * @return
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }


    /**
     * 功能描述:Map 集合导出
     *
     * @author HeJD
     * @date 2018/10/9 13:54
     * @param list 实体集合
     * @param fileName 导出的文件名称
     * @param response
     * @return
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    /**
     * 功能描述:默认导出方法
     *
     * @author HeJD
     * @date 2018/10/9 13:54
     * @param list 导出的实体集合
     * @param fileName 导出的文件名
     * @param pojoClass pojo实体
     * @param exportParams ExportParams封装实体
     * @param response
     * @return
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }

    /**
     * 功能描述:Excel导出
     *
     * @author HeJD
     * @date 2018/10/9   15:35
     * @param fileName 文件名称
     * @param response
     * @param workbook Excel对象
     * @return
     */
    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);
        }
    }

    /**
     * 功能描述:默认导出方法
     *
     * @author HeJD
     * @date 2018/7/23 15:33
     * @param list 导出的实体集合
     * @param fileName 导出的文件名
     * @param response
     * @return
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) ;

        downLoadExcel(fileName, response, workbook);
    }


    /**
     * 功能描述:根据文件路径来导入Excel
     *
     * @author HeJD
     * @date 2018/10/9 14:17
     * @param filePath 文件路径
     * @param titleRows 表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass Excel实体类
     * @return
     */
    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) {
            e.printStackTrace();

        }
        return list;
    }

    /**
     * 功能描述:根据接收的Excel文件来导入Excel,并封装成实体类
     *
     * @author HeJD
     * @date 2018/10/9 14:17
     * @param file 上传的文件
     * @param titleRows 表标题的行数
     * @param headerRows 表头行数
     * @param pojoClass Excel实体类
     * @return
     */
    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.getMessage());

        }
        return list;
    }


    /**
     * 接口導出
     * 注意这里的HttpResponse是我自己自定义类,具体使用时可以用JSONObject返回
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName
     * @return
     */
    public static HttpResponse pcExportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName)
    {
        return pcExport(list, pojoClass, fileName, new ExportParams(title, sheetName));
    }

    private static HttpResponse pcExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            return PcExportExcel(fileName, workbook);
        }else
        {
            return HttpResponse.createByErrorMessage("导出失败");
        }
    }

    private static HttpResponse PcExportExcel(String fileName, Workbook workbook) {
        HttpResponse resp = new HttpResponse();
        try
        {
            File file=  new File("/usr/local/mdsoftware/wwwroot/BaoXianYuYue/upload-dir/uploadfiles/exportExcel/exportExcel.xls");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream);
            resp.setCode(200);
            resp.setMsg("导出成功,地址:");
            resp.setData("http://211.149.227.130:8083/uploadfiles/exportExcel/exportExcel.xls");
            return resp;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

3. java实现代码

	/**
     * 导出Excel
     * searchWord和name 为前端传来的参数
     */
    @RequestMapping("/exportInfo")
    @ResponseBody
    public synchronized void exportExcel(HttpServletResponse response,
                                         String searchWord, String name)
    {
    	//map插入查询条件
        Map<String, Object> map = new HashMap<>();
        map.put("searchWord", searchWord);
        map.put("name", name);

		//根据map存储的查询条件 调用Service发送sql语句返回list,这里具体情况具体分析
        List<GoodsDO> list = goodsService.list(map).getList();

        //设置表名,引脚名,文件格式,及写入list数据到excel中
        EasyPoiUtil.exportExcel(list, "产品", "产品詳細信息", GoodsDO.class, "goodsInfo.xls", response);
    }

4. PoJo层添加@Excel注解

import java.io.Serializable;
import cn.afterturn.easypoi.excel.annotation.Excel;

/**
 * 产品
 * @author Jesse
 * @date 2020-03-04 16:13:36
 */
public class GoodsDO implements Serializable {
	private static final long serialVersionUID = 1L;
	
   
   	//id
	private Long id;
      
   //品类
   @Excel(name = "品类",width = 25)   //导出导入的Excel单元格名
   private String varieties;
      
   //规格
   @Excel(name = "规格",width = 25)
   private String specification;
      
   //推送方式
   @Excel(name = "推送方式",replace = { "短信_2", "模板消息_1"})	//用数字判断赋单元格值
   private Integer messageType;
   
}

EasyPoi还支持一对多导出
使用注解: @ExcelCollection(name = “子订单”)

发布了6 篇原创文章 · 获赞 0 · 访问量 839

猜你喜欢

转载自blog.csdn.net/weixin_43910274/article/details/104914740