EasyPOI完美實現導入導出,實用簡單,一行代碼即可

開發中經常會遇到excel的處理,導入導出解析等等。正好最近在項目裏面需要用到EasyPOI,非常

容易,簡單上手,一行代碼實現導入導出。

1、導入maven依賴

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.0.0</version>
</dependency>

在springboot項目裏面也可以使用如下座標

<dependency>

       <groupId>cn.afterturn</groupId>

       <artifactId>easypoi-spring-boot-starter</artifactId>

       <version>4.0.0</version>

   </dependency>

 

2、導出功能

前端頁面:

 

<form class="layui-form" action="/load" οnsubmit="return false" id="form">

    <div class="layui-form-item">

        <label class="layui-form-label">經辦人</label>

        <div class="layui-input-inline">

            <input type="text" name="transactor" id="transactor" placeholder="請輸入經辦人" autocomplete="off" class="layui-input">

        </div>

    </div>

    <div class="layui-form-item">

        <label class="layui-form-label">摘要</label>

        <div class="layui-input-inline">

            <input type="text" name="summary" id="summary" placeholder="請輸入摘要" autocomplete="off" class="layui-input">

        </div>

    </div>

    <div class="layui-form-item">

        <label class="layui-form-label">選擇時間</label>

        <div class="layui-input-inline">

            <input type="text" name="opetime" id="opetime" placeholder="請選擇時間範圍" autocomplete="off"

                   class="layui-input">

        </div>

    </div>

    <div class="layui-form-item">

        <div class="layui-input-block">

            <button class="layui-btn" lay-submit id="loadBt">導出</button>

         </button>-->

        </div>

    </div>

</form>

 

<script>

    layui.use(['layer', 'laydate'], function () {

        var layer = layui.layer;

        var laydate = layui.laydate;

        laydate.render({

            elem: '#opetime',

            type:'date',

            range:true,//開啓左右面板,可以進行日期範圍的選擇,很好用

            //trigger:'mouseover',//定義鼠標懸停時彈出控件

            theme:'#393D49',//主題顏色

            calendar:true//是否顯示公曆節日

        });

    });



    layui.use('form', function () {

        var form = layui.form;

        var $ = layui.$;

        $("#loadBt").click(function () {

            transactor = $("#transactor").val(),

            summary = $("#summary").val(),

            opetime=$("#opetime").val();

            $("#form").attr("onsubmit", "return true");

            $("#form").submit();

            $("#form").attr("onsubmit", "return false");

        });

     });

</script>

後臺Controller層代碼

/**

 * @Author Steel.D

 * @Description

 * @Date  2019-7-30 16:45

 * @Param  excel的模型集合,請求,響應

 * @return

 **/



@RequestMapping("/load")

public  void loadExcel(ModelMap map, HttpServletRequest request,

                       HttpServletResponse response){

    //將接收的參數進行處理

    String transactor = request.getParameter("transactor");

    String summary = request.getParameter("summary");

    String opetime = request.getParameter("opetime");

    //傳過來的數據格式爲2019-09-12 - 2019-09-30 需要進行處理

    opetime = opetime.replaceAll(" ", "");

    Map<String,Object> params1 = new HashMap<>();

    if ( StringUtils.isNotEmpty(opetime)){

        String substring = opetime.substring(0, 10);

        String substring1 = opetime.substring(11);

        Date date = DateUtils.strToDate(substring);

        Date date1 = DateUtils.strToDate(substring1);

        params1.put("opetime",date);

        params1.put("endtime",date1);

    }

    params1.put("transactor",transactor);

    params1.put("summary",summary);

    List<Finance> bills = financeDao.all(params1);

    ExportParams params = new ExportParams("流水詳情", "概覽", ExcelType.XSSF);

    params.setFreezeCol(2);

    map.put(NormalExcelConstants.DATA_LIST, bills);

    map.put(NormalExcelConstants.CLASS, Finance.class);

    map.put(NormalExcelConstants.PARAMS, params);

    map.put(NormalExcelConstants.FILE_NAME, "編易教育賬單流水");

    //封裝數據進行數據導出 PoiBaseView.render(map,request,response,NormalExcelConstants.EASYPOI_EXCEL_VIEW);
}

 

3、導入Excel功能

前端代碼:

<form class="layui-form" action="/upload" enctype="multipart/form-data" method="post">

    <input type="file" name="file"><br>

    <input type="submit" value="提交" id="submit">

</form>

後臺Controller,一行代碼實現Excel解析

/**

 * @Author Steel.D

 * @Description 

 * @Date  2019-7-31 17:32

 * @Param 

 * @return

 **/



@PostMapping("/upload")

public ResponseInfo upload(@RequestParam("file") MultipartFile file){
//上傳的Excel進行數據模型解析封裝 ,四個參數分別爲,上傳的文件,excel表標題行數,頭行數,實體類class

    List<TStudent> tStudents = EasyPoiUtil.importExcel(file, 1, 1, TStudent.class);

    studentService.sava(tStudents);

    return new ResponseInfo("1","成功");

}

 

EasyPOI非常實用的一個工具類:

/**

 * @Author Steel.D

 * @Description   easypoi導入導出通用工具類

 * @Date  2019-7-31 9:29

 * @Param

 * @return

 **/

public class EasyPoiUtil {

    /**

     * 功能描述:複雜導出Excel,包括文件名以及表名。創建表頭

     *

     * @author Steel.D

     * @Date 2019-7-31 9:30

     * @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 Steel.D

     * @Date 2019-7-31 9:35

     * @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 Steel.D

     * @Date 2019-7-31 9:45

     * @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 Steel.D

     * @Date 2019-7-31 9:50

     * @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 Steel.D

     * @Date 2019-7-31 10: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 SteeL.D

     * @Date 2019-7-31 10:45

     * @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 Steel.D

     * @Date 2019-7-31 11:05

     * @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 Steel.D

     * @Date 2019-7-31 11:30

     * @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;

    }



}

實體類導出的時候需要用到@Excel註解

@Excel(name="賬單id")

private Integer id;

@Excel(name="經辦人")

private String transactor;

@Excel(name = "摘要")

private String summary;

@Excel(name="詳情",width = 50)

private String details;

@Excel(name="收入")

private Integer income;

@Excel(name = "支出")

private Integer payment;

@Excel(name = "累計")

private Integer count;

@Excel(name = "備註",width = 20)

private String comments;

@Excel(name="處理時間",exportFormat ="yyyy-MM-dd HH:mm:ss",width = 30)

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章