使用EasyPoi进行对Excel表格的导入、导出

添加EasyPoi依赖

<properties>
      <easypoi.version>3.1.0</easypoi.version>
</properties>

<dependencies>
<!--EasyPoi-->
      <dependency>
            <groupId>cn.afterturn</groupId>
	    <artifactId>easypoi-base</artifactId>
	    <version>${easypoi.version}</version>
      </dependency>
      <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>${easypoi.version}</version>
      </dependency>
      <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>${easypoi.version}</version>
      </dependency>
</dependencies>

EasyPoi工具类

/**
 * Excel导入导出工具类
 */

public class ExcelUtils {

    /**
     * excel 导出
     *
     * @param list     数据列表
     * @param fileName 导出时的excel名称
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list     数据列表
     * @param fileName 导出时的excel名称
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param response
     * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
     * @param response
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据列表
     * @param title     表格内数据标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  导出时的excel名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }



    /**
     * excel 导出
     *
     * @param list           数据列表
     * @param title          表格内数据标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       导出时的excel名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }


    /**
     * excel下载
     *
     * @param fileName 下载时的文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }



    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param filePath   excel文件路径
     * @param titleRows  表格内数据标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /**
     * excel 导入
     *
     * @param file       上传的文件
     * @param titleRows  表格内数据标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   表格内数据标题行
     * @param headerRows  表头行
     * @param pojoClass   pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

实体类注解

@Data
public class DongBei implements Serializable {
    @Excel(name = "序号",width = 20,orderNum = "0") // 首列
    private String id;
    @Excel(name = "名称",width = 20,orderNum = "1") 
    private String keyName;
    @Excel(name = "数据类型",width = 20,orderNum = "2")
    private String dataType;
    @Excel(name = "设备类型",width = 20,orderNum = "3")
    private String deviceType;
}

工具类的使用

    /**
     * 导出
     */
    @RequestMapping(value = "/downLoadExcel", method = RequestMethod.GET)
    @ResponseBody
    public void downLoadExcel(HttpServletRequest request , HttpServletResponse response) {
        try {
            String title = "信息表"; //标题名
            String sheetName = "信息表"; //表名
            ArrayList<Sys_User> list = new ArrayList<>();
            ExcelUtils.exportExcel(list, title, sheetName, DongBei.class, "user" + System.currentTimeMillis(), response);
        } catch (Exception e) {
            log.error(e.getMessage(), e.fillInStackTrace());
        }
    }

    /**
     *导入
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public void importSS(@RequestParam("file") MultipartFile file) {
        List<DongBei> iotCollectionPoints = null;
        int filed = 0;
        int success = 0;
        try {
            iotCollectionPoints = ExcelUtils.importExcel(file, DongBei.class);
            IotCollPointIsMain coll = new IotCollPointIsMain();
            for (DongBei pointIsMain : iotCollectionPoints) {
                try {
                    coll.setMinValues("0");
                    coll.setMaxValues("10000");
                    coll.setCreateTime(date);
                    coll.setId(UniqueIdUtil.genId());
                    coll.setCreateUser(userId);
                    coll.setIsDelete("0");
                    coll.setIsReadOnly("110");
                    coll.setStatus("0");
                    //Tag名称
                    coll.setKeyName(pointIsMain.getKeyName());
                    coll.setName(pointIsMain.getKeyName());
                    coll.setCreatetime(date);
                    coll.setCreateBy(userId);
                    iotCollPointIsMainService.saveColl(coll);
                    success++;
                } catch (Exception e) {
                    filed++;
                    logger.error(e.getMessage(), e.fillInStackTrace());
                }
            }
            System.out.println("成功导入数据:" + success + "条 , 失败" + filed + "条");
        } catch (Exception e) {
            logger.error(e.getMessage(), e.fillInStackTrace());
        }

本篇文章为自用而记录

posted @ 2021-01-15 15:20  张震-Miles  阅读(5872)  评论(0编辑  收藏  举报