easyexcell导出专题

 

 

本文介绍阿里巴巴导出工具easyexcell导出excell

介绍一下几种导出情况

1,导出单个sheet,无模型方式

2,导出单个sheet,模型方式

3,导出多个sheet,无模型方式

4,导出多个sheet,模型方式

5,导出多个sheet,到本地指定目录下

以上导出方式区别

1,(1-4)自动下载到c盘默认路径并创建文件;方式5,下载到指定目录及文件下

区别在于输出流的的创建

easyexcell导出专题_第1张图片

2,无模型方式,模型方式区别

2.1,前者不需要定义导出实体类,手动封装数表头信息及导出数据

且封装表头数据方式有两种,sheet和table

1)sheet

封装表头

  Sheet sheetMing = new Sheet(1, 0);
        sheetMing.setSheetName("沈明内购方案信息");
        //设置列
        List> titlesMing = new ArrayList<>();
        titlesMing.add(Arrays.asList("方案编号"));
        titlesMing.add(Arrays.asList("主机厂"));
        titlesMing.add(Arrays.asList("方案名称"));
        titlesMing.add(Arrays.asList("可购品牌"));
        titlesMing.add(Arrays.asList("可购车型"));
        titlesMing.add(Arrays.asList("附件"));
        titlesMing.add(Arrays.asList("状态"));
        titlesMing.add(Arrays.asList("备注"));
        titlesMing.add(Arrays.asList("审批人"));
        titlesMing.add(Arrays.asList("审批时间"));
        titlesMing.add(Arrays.asList("审批意见"));
        titlesMing.add(Arrays.asList("创建人"));
        titlesMing.add(Arrays.asList("创建时间"));
        titlesMing.add(Arrays.asList("修改人"));
        titlesMing.add(Arrays.asList("修改日期"));
        sheetMing.setHead(titlesMing);

注意表头每一列用List包装,setHead()入参是表头集合的集合 

  public void setHead(List> head) {
        this.head = head;
    }

封装数据 

  List> dataMing = new ArrayList<>();
        for (PlanVO object : listMing) {
            List list = new ArrayList<>();
            list.add(object.getCode());
            list.add(object.getBrandName());
            list.add(object.getName());
            list.add(object.getBrandNameList());
            list.add(object.getVehicleTypeName());
            list.add(object.getFileName().toString());
            list.add(object.getStatusName());
            list.add(object.getDescription());
            list.add(object.getApprovalUser());
            list.add(DateUtil.getNormTime(object.getApprovalTime()));
            list.add(object.getApprovalResult());
            list.add(object.getCreateUser());
            list.add(DateUtil.getNormTime(object.getCreateTime()));
            list.add(object.getUpdateUser());
            list.add(DateUtil.getNormTime(object.getUpdateTime()));
            dataMing.add(list);
        }

 写入导出数据

  public ExcelWriter write0(List> data, Sheet sheet, Table table) {
        excelBuilder.addContent(data, sheet, table);
        return this;
    }

2) table

 private void excellReport(List planVO, HttpServletResponse servletResponse) {
        ExcelWriter writer = new ExcelWriter(getOutputStream("已发布内购方案", servletResponse), ExcelTypeEnum.XLSX);
        //设置SHEET
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("sheet1");

        //设置列
        Table table = new Table(1);
        List> titles = new ArrayList<>();
        titles.add(Arrays.asList("方案编号"));
        titles.add(Arrays.asList("主机厂"));
        titles.add(Arrays.asList("方案名称"));
        titles.add(Arrays.asList("可购品牌"));
        titles.add(Arrays.asList("可购车型"));
        titles.add(Arrays.asList("附件"));
        titles.add(Arrays.asList("状态"));
        titles.add(Arrays.asList("备注"));
        titles.add(Arrays.asList("审批人"));
        titles.add(Arrays.asList("审批时间"));
        titles.add(Arrays.asList("审批意见"));
        titles.add(Arrays.asList("创建人"));
        titles.add(Arrays.asList("创建时间"));
        titles.add(Arrays.asList("修改人"));
        titles.add(Arrays.asList("修改日期"));
        table.setHead(titles);

        // 封装数据
        List> userList = new ArrayList<>();
        for (PlanVO object : planVO) {
            List list = new ArrayList<>();
            list.add(object.getCode());
            list.add(object.getBrandName());
            list.add(object.getName());
            list.add(object.getBrandNameList());
            list.add(object.getVehicleTypeName());
            list.add(object.getFileName().toString());
            list.add(object.getStatusName());
            list.add(object.getDescription());
            list.add(object.getApprovalUser());
            list.add(DateUtil.getNormTime(object.getApprovalTime()));
            list.add(object.getApprovalResult());
            list.add(object.getCreateUser());
            list.add(DateUtil.getNormTime(object.getCreateTime()));
            list.add(object.getUpdateUser());
            list.add(DateUtil.getNormTime(object.getUpdateTime()));
            userList.add(list);
        }
        writer.write0(userList, sheet, table);
        writer.finish();
    }

写入数据调用方法

 public ExcelWriter write0(List> data, Sheet sheet, Table table) {
        excelBuilder.addContent(data, sheet, table);
        return this;
    }

2.2,后者需要定义导出实体类,指定表头及顺序

实体类

@EqualsAndHashCode(callSuper = true)
@Data
public class TableHeaderExcelProperty extends BaseRowModel {

    /**
     * value: 表头名称
     * index: 列的号, 0表示第一列
     */
    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    private int age;

    @ExcelProperty(value = "学校", index = 2)
    private String school;

}

调用方法

 public ExcelWriter write(List data, Sheet sheet) {
        excelBuilder.addContent(data, sheet);
        return this;
    }

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------上面大概介绍了一下,下面详细介绍每一种方式

一,导出单个sheet,无模型方式

sheet封装表头

  private void excellReport(List planVO, HttpServletResponse servletResponse) {
        ExcelWriter writer = new ExcelWriter(getOutputStream("已发布内购方案", servletResponse), ExcelTypeEnum.XLSX);
        //设置SHEET
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("sheet1");

        //设置列
        Table table = new Table(1);
        List> titles = new ArrayList<>();
        titles.add(Arrays.asList("方案编号"));
        titles.add(Arrays.asList("主机厂"));
        titles.add(Arrays.asList("方案名称"));
        titles.add(Arrays.asList("可购品牌"));
        titles.add(Arrays.asList("可购车型"));
        titles.add(Arrays.asList("附件"));
        titles.add(Arrays.asList("状态"));
        titles.add(Arrays.asList("备注"));
        titles.add(Arrays.asList("审批人"));
        titles.add(Arrays.asList("审批时间"));
        titles.add(Arrays.asList("审批意见"));
        titles.add(Arrays.asList("创建人"));
        titles.add(Arrays.asList("创建时间"));
        titles.add(Arrays.asList("修改人"));
        titles.add(Arrays.asList("修改日期"));
        table.setHead(titles);

        // 封装数据
        List> userList = new ArrayList<>();
        for (PlanVO object : planVO) {
            List list = new ArrayList<>();
            list.add(object.getCode());
            list.add(object.getBrandName());
            list.add(object.getName());
            list.add(object.getBrandNameList());
            list.add(object.getVehicleTypeName());
            list.add(object.getFileName().toString());
            list.add(object.getStatusName());
            list.add(object.getDescription());
            list.add(object.getApprovalUser());
            list.add(DateUtil.getNormTime(object.getApprovalTime()));
            list.add(object.getApprovalResult());
            list.add(object.getCreateUser());
            list.add(DateUtil.getNormTime(object.getCreateTime()));
            list.add(object.getUpdateUser());
            list.add(DateUtil.getNormTime(object.getUpdateTime()));
            userList.add(list);
        }
        writer.write0(userList, sheet, table);
        writer.finish();
    }

创建输出流 

 /**
     * 导出文件时为Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        //创建本地文件
        String filePath = fileName + ".xlsx";

        File dbfFile = new File(filePath);
        try {
            if (!dbfFile.exists() || dbfFile.isDirectory()) {
                dbfFile.createNewFile();
            }
            fileName = new String(filePath.getBytes(), "ISO-8859-1");
            response.addHeader("Content-Disposition", "filename=" + fileName);
            return response.getOutputStream();
        } catch (IOException e) {
            throw new ExcelException("创建文件失败!");
        }
    }

二,导出单个sheet,模型方式

 @org.junit.Test
    public void writeWithTemplate() {
        String filePath = "D:\\share\\model.xlsx";
        List data = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty();
            tableHeaderExcelProperty.setName("cmj" + i);
            tableHeaderExcelProperty.setAge(22 + i);
            tableHeaderExcelProperty.setSchool("清华大学" + i);
            data.add(tableHeaderExcelProperty);
        }
        ExcelUtil.writeWithTemplate(filePath, data);
    }

详细方法见工具类

三,导出多个sheet,无模型方式和有模型方式

效果图

easyexcell导出专题_第2张图片

easyexcell导出专题_第3张图片 Controller

    /**
     * 导出多个sheet 且表头,内容不同
     * 无模型方式
     * @param servletResponse
     * @param request
     */
    @RequestMapping(value = "/export/duogeSheet")
    @LoggerManage(description = "导出多个sheet")
    public void exportDuogeSheet(HttpServletResponse servletResponse, BaseRequestModel request) {
        try {
            excelDemoSercice.exportDuogeSheet(servletResponse, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出多个sheet 且表头,内容不同
     * 有模型方式
     * @param servletResponse
     */
    @RequestMapping(value = "/export/duogeSheetModel")
    @LoggerManage(description = "导出多个sheet,模型方式")
    public void exportDuogeSheetModel(HttpServletResponse servletResponse) {
        try {
            excelDemoSercice.exportDuogeSheetModel(servletResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 serviceImpl

/**
     * 无模型方式导出数据
     * @param servletResponse
     * @param request
     */
    public void exportDuogeSheet(HttpServletResponse servletResponse, BaseRequestModel request) {
        // 查询数据shenming
        List listMing = queryDataMing(request);

        // 查询数据-其他
        List listOther = queryData(request);

        ExcelWriter writer = new ExcelWriter(getOutputStream("已发布内购方案+购车方案", servletResponse), ExcelTypeEnum.XLSX);

        //内购方案-----------
        //设置SHEET
        Sheet sheetMing = new Sheet(1, 0);
        sheetMing.setSheetName("沈明内购方案信息");
        //设置列
        List> titlesMing = new ArrayList<>();
        titlesMing.add(Arrays.asList("方案编号"));
        titlesMing.add(Arrays.asList("主机厂"));
        titlesMing.add(Arrays.asList("方案名称"));
        titlesMing.add(Arrays.asList("可购品牌"));
        titlesMing.add(Arrays.asList("可购车型"));
        titlesMing.add(Arrays.asList("附件"));
        titlesMing.add(Arrays.asList("状态"));
        titlesMing.add(Arrays.asList("备注"));
        titlesMing.add(Arrays.asList("审批人"));
        titlesMing.add(Arrays.asList("审批时间"));
        titlesMing.add(Arrays.asList("审批意见"));
        titlesMing.add(Arrays.asList("创建人"));
        titlesMing.add(Arrays.asList("创建时间"));
        titlesMing.add(Arrays.asList("修改人"));
        titlesMing.add(Arrays.asList("修改日期"));
        sheetMing.setHead(titlesMing);

        // 封装数据
        List> dataMing = new ArrayList<>();
        for (PlanVO object : listMing) {
            List list = new ArrayList<>();
            list.add(object.getCode());
            list.add(object.getBrandName());
            list.add(object.getName());
            list.add(object.getBrandNameList());
            list.add(object.getVehicleTypeName());
            list.add(object.getFileName().toString());
            list.add(object.getStatusName());
            list.add(object.getDescription());
            list.add(object.getApprovalUser());
            list.add(DateUtil.getNormTime(object.getApprovalTime()));
            list.add(object.getApprovalResult());
            list.add(object.getCreateUser());
            list.add(DateUtil.getNormTime(object.getCreateTime()));
            list.add(object.getUpdateUser());
            list.add(DateUtil.getNormTime(object.getUpdateTime()));
            dataMing.add(list);
        }

        // 购车申请
        //设置SHEET
        Sheet sheetOther = new Sheet(2, 0);
        sheetOther.setSheetName("其他用户内购方案信息");
        //设置列
        List> titlesOther = new ArrayList<>();
        titlesOther.add(Arrays.asList("方案编号1"));
        titlesOther.add(Arrays.asList("主机厂1"));
        titlesOther.add(Arrays.asList("方案名称1"));
        titlesOther.add(Arrays.asList("可购品牌1"));
        titlesOther.add(Arrays.asList("可购车型1"));
        titlesOther.add(Arrays.asList("附件1"));
        titlesOther.add(Arrays.asList("状态1"));
        titlesOther.add(Arrays.asList("备注1"));
        titlesOther.add(Arrays.asList("审批人1"));
        titlesOther.add(Arrays.asList("审批时间1"));
        titlesOther.add(Arrays.asList("审批意见1"));
        titlesOther.add(Arrays.asList("创建人1"));
        titlesOther.add(Arrays.asList("创建时间1"));
        titlesOther.add(Arrays.asList("修改人1"));
        titlesOther.add(Arrays.asList("修改日期1"));
        sheetOther.setHead(titlesOther);

        // 封装数据
        List> dataOther = new ArrayList<>();
        for (PlanVO object : listOther) {
            List list = new ArrayList<>();
            list.add(object.getCode());
            list.add(object.getBrandName());
            list.add(object.getName());
            list.add(object.getBrandNameList());
            list.add(object.getVehicleTypeName());
            list.add(object.getFileName().toString());
            list.add(object.getStatusName());
            list.add(object.getDescription());
            list.add(object.getApprovalUser());
            list.add(DateUtil.getNormTime(object.getApprovalTime()));
            list.add(object.getApprovalResult());
            list.add(object.getCreateUser());
            list.add(DateUtil.getNormTime(object.getCreateTime()));
            list.add(object.getUpdateUser());
            list.add(DateUtil.getNormTime(object.getUpdateTime()));
            dataOther.add(list);
        }


        writer.write0(dataMing, sheetMing);
        writer.write0(dataOther, sheetOther);
        writer.finish();
    }

    /**
     * 沈明查询导出数据
     *
     * @param request
     * @return
     */
    public List queryDataMing(BaseRequestModel request) {
        // PlanVO vo = JSON.parseObject(request.getReqData().toString(), PlanVO.class);
        // Test
        PlanVO vo = new PlanVO();
        //vo.setBrandId(Long.parseLong("100"));
        vo.setStatus(PlanStatusE.PUBLISHED.getValue());
        List list = planMapper.selectPlanByStatus(vo);

        List> isDelDict = DictUtils.getDictListByCode(DictTypeE.IS_DEL_CODE.getTypeCode());
        List> statusDict = DictUtils.getDictListByCode(DictTypeE.PLAN_STATUS.getTypeCode());
        list.forEach(v -> {
            v.setIsDelName(DictUtils.getDictKeyByValue(v.getIsDel(), isDelDict));
            v.setStatusName(DictUtils.getDictKeyByValue(v.getStatus(), statusDict));

            // 附件
            Map map = new HashMap<>();
            PlanFileEntity planFileEntity = new PlanFileEntity();
            planFileEntity.setPlanId(v.getId());
            planFileEntity.setIsDel(DeleteStatusE.USEFUL.getValue());
            List pfList = planFileMapper.select(planFileEntity);
            List files = new ArrayList<>();
            pfList.forEach(f -> {
                files.add(f.getFileName());
            });
            v.setFileName(files);
            map.put("file", pfList);
            v.setMap(map);
        });
        return list;
    }

    public List queryData(BaseRequestModel request) {
        //PlanVO vo = JSON.parseObject(request.getReqData().toString(), PlanVO.class);
        // Test
        PlanVO vo = new PlanVO();
        vo.setBrandId(Long.parseLong("99"));
        Integer userType = 0;
        Long belongTo = Long.valueOf("754");

        Integer page = 0;
        Integer size = 2147483647;

      /*  Integer userType = request.getUserType();
        Long belongTo = request.getBelongTo();*/

        List planVOList = new ArrayList<>();
        List branIdList = new ArrayList<>();
        List orgIds = new ArrayList<>();

        // 主机厂用户
        if (UserTypeE.ORG.getValue().equals(userType)) {
            orgIds.add(belongTo);
        }
        // 经销商用户
        else if (UserTypeE.DEALER.getValue().equals(userType)) {
            branIdList = dealerMapper.selectBrandIdByDealerId(belongTo);
            // 品牌取主机厂
            if (branIdList != null && !branIdList.isEmpty()) {
                Map map = new HashMap<>();
                map.put("branIdList", branIdList);
                orgIds = orgMapper.selectOrgByBrand(map);
            }
            //企业用户
        } else {
            CompanyEntity companyEntity = companyManageMapper.selectByPrimaryKey(belongTo);
            if (companyEntity != null) {
                String companyLevel = companyEntity.getCompanyLevel();
                // 二级用户以下取二级企业ID
                if (!CompanyTypeE.CONGLOMERATE.getValue().toString().equals(companyLevel) && !CompanyTypeE.SUBORDINATEENTERPRISE.getValue().toString().equals(companyLevel)) {
                    belongTo = companyEntity.getApprovalCompany().longValue();
                }

                // 过滤主机厂
                Long brandId = vo.getBrandId();
                planVOList = planMapper.selectPlanByCompanyId(brandId, belongTo, PlanStatusE.PUBLISHED.getValue(), page, size);
                //total = planMapper.selectTotalPlanByCompanyId(brandId, belongTo, PlanStatusE.PUBLISHED.getValue(), page, size);
            }
        }

        // 主机厂,经销商用户
        // 1,同时勾选主机厂,过滤当前主机厂
        if (UserTypeE.ORG.getValue().equals(userType) || UserTypeE.DEALER.getValue().equals(userType)) {
            List orgIdFilt = new ArrayList<>();
            Long brandId = vo.getBrandId();
            if (brandId != null) {
                for (Long org : orgIds) {
                    if (org.equals(brandId)) {
                        orgIdFilt.add(org);
                    }
                }
                if (orgIdFilt != null && !orgIdFilt.isEmpty()) {
                    planVOList = planMapper.selectPlanByOrgIds(orgIdFilt, PlanStatusE.PUBLISHED.getValue(), page, size);
                    //total = planMapper.selectPlanByOrgIdsTotal(orgIdFilt, PlanStatusE.PUBLISHED.getValue(), page, size);
                } else {
                    return Arrays.asList();
                }
            }
            // 2,没勾选主机厂,直接查询
            if (brandId == null && orgIds != null && !orgIds.isEmpty()) {
                planVOList = planMapper.selectPlanByOrgIds(orgIds, PlanStatusE.PUBLISHED.getValue(), page, size);
                //total = planMapper.selectPlanByOrgIdsTotal(orgIds, PlanStatusE.PUBLISHED.getValue(), page, size);
            }
        }

        // 处理返回数据
        voHandle(planVOList);
        return planVOList;
    }

    /**
     * 处理返回数据
     *
     * @param planVOList
     * @return
     */
    public void voHandle(List planVOList) {
        List> isDelDict = DictUtils.getDictListByCode(DictTypeE.IS_DEL_CODE.getTypeCode());
        List> statusDict = DictUtils.getDictListByCode(DictTypeE.PLAN_STATUS.getTypeCode());
        planVOList.forEach(v -> {
            v.setIsDelName(DictUtils.getDictKeyByValue(v.getIsDel(), isDelDict));
            v.setStatusName(DictUtils.getDictKeyByValue(v.getStatus(), statusDict));  // 附件

            Map map = new HashMap<>();
            PlanFileEntity planFileEntity = new PlanFileEntity();
            planFileEntity.setPlanId(v.getId());
            planFileEntity.setIsDel(DeleteStatusE.USEFUL.getValue());
            List pfList = planFileMapper.select(planFileEntity);
            List files = new ArrayList<>();
            pfList.forEach(f -> {
                files.add(f.getFileName());
            });
            v.setFileName(files);
            map.put("file", pfList);
            v.setMap(map);
        });
    }

    /**
     * 使用模型方式导出
     *
     * @param servletResponse
     */
    public void exportDuogeSheetModel(HttpServletResponse servletResponse) {
        List listData = new ArrayList<>();
        // sheet1
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty();
            tableHeaderExcelProperty.setName("shenke" + i);
            tableHeaderExcelProperty.setAge(29 + i);
            tableHeaderExcelProperty.setSchool("阜阳师范大学" + i);
            list.add(tableHeaderExcelProperty);
        }
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("个人基本信息");

        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(list);
        multipleSheelPropety.setSheet(sheet);

        // sheet2
        List listCom = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            TableHeaderExcelPropertyTwo tableHeaderExcelPropertyTwo = new TableHeaderExcelPropertyTwo();
            tableHeaderExcelPropertyTwo.setName("shenke" + i);
            tableHeaderExcelPropertyTwo.setCompany("法本" + i);
            tableHeaderExcelPropertyTwo.setSalary("100" + i);
            listCom.add(tableHeaderExcelPropertyTwo);
        }
        Sheet sheetCom = new Sheet(2, 0);
        sheetCom.setSheetName("个人公司信息");

        ExcelUtil.MultipleSheelPropety multipleSheelPropetyCom = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropetyCom.setData(listCom);
        multipleSheelPropetyCom.setSheet(sheetCom);

        // 封装数据
        listData.add(multipleSheelPropety);
        listData.add(multipleSheelPropetyCom);

        ExcelUtil.writeWithMultipleSheel("个人基本和公司信息导出", listData, servletResponse);
    }

entity 模型方式

@EqualsAndHashCode(callSuper = true)
@Data
public class TableHeaderExcelProperty extends BaseRowModel {

    /**
     * value: 表头名称
     * index: 列的号, 0表示第一列
     */
    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    private int age;

    @ExcelProperty(value = "学校", index = 2)
    private String school;

}
@EqualsAndHashCode(callSuper = true)
@Data
public class TableHeaderExcelPropertyTwo extends BaseRowModel {

    /**
     * value: 表头名称
     * index: 列的号, 0表示第一列
     */
    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "公司", index = 1)
    private String company;

    @ExcelProperty(value = "年薪", index = 2)
    private String salary;

}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

测试及工具类

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestExcell {

    /**
     * 读取少于1000行的excle
     */
    @org.junit.Test
    public void readLessThan1000Row() {
        String filePath = "/home/chenmingjian/Downloads/测试.xlsx";
        List objects = ExcelUtil.readLessThan1000Row(filePath);
        objects.forEach(System.out::println);
    }

    /**
     * 读取少于1000行的excle,可以指定sheet和从几行读起
     */
    @org.junit.Test
    public void readLessThan1000RowBySheet() {
        String filePath = "/home/chenmingjian/Downloads/测试.xlsx";
        Sheet sheet = new Sheet(1, 1);
        List objects = ExcelUtil.readLessThan1000RowBySheet(filePath, sheet);
        objects.forEach(System.out::println);
    }

    /**
     * 读取大于1000行的excle
     * 带sheet参数的方法可参照测试方法readLessThan1000RowBySheet()
     */
    @org.junit.Test
    public void readMoreThan1000Row() {
        String filePath = "/home/chenmingjian/Downloads/测试.xlsx";
        List objects = ExcelUtil.readMoreThan1000Row(filePath);
        objects.forEach(System.out::println);
    }


    /**
     * 生成excle
     * 带sheet参数的方法可参照测试方法readLessThan1000RowBySheet()
     */
    @org.junit.Test
    public void writeBySimple() {
        String filePath = "D:\\share\\noModel.xlsx";
        List> data = new ArrayList<>();
        data.add(Arrays.asList("111", "222", "333"));
        data.add(Arrays.asList("111", "222", "333"));
        data.add(Arrays.asList("111", "222", "333"));
        List head = Arrays.asList("表头1", "表头2", "表头3");
        ExcelUtil.writeBySimple(filePath, data, head);
    }


    /**
     * 生成excle, 带用模型
     * 带sheet参数的方法可参照测试方法readLessThan1000RowBySheet()
     */
    @org.junit.Test
    public void writeWithTemplate() {
        String filePath = "D:\\share\\model.xlsx";
        List data = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty();
            tableHeaderExcelProperty.setName("cmj" + i);
            tableHeaderExcelProperty.setAge(22 + i);
            tableHeaderExcelProperty.setSchool("清华大学" + i);
            data.add(tableHeaderExcelProperty);
        }
        ExcelUtil.writeWithTemplate(filePath, data);
    }


    /**
     * 生成excle, 带用模型,带多个sheet
     */
    @org.junit.Test
    public void writeWithMultipleSheel() {
        List list1 = new ArrayList<>();
        for (int j = 1; j < 4; j++) {
            List list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty();
                tableHeaderExcelProperty.setName("shenke" + i);
                tableHeaderExcelProperty.setAge(29 + i);
                tableHeaderExcelProperty.setSchool("阜阳师范大学" + i);
                list.add(tableHeaderExcelProperty);
            }

            Sheet sheet = new Sheet(j, 0);
            sheet.setSheetName("sheet" + j);

            ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
            multipleSheelPropety.setData(list);
            multipleSheelPropety.setSheet(sheet);

            list1.add(multipleSheelPropety);
        }
        ExcelUtil.writeWithMultipleSheel("D:\\share\\modelSheets.xlsx", list1);
    }

    /**
     * 优化
     * 生成excle, 带用模型,带多个sheet
     * 不同sheet名称和数据不同
     */
    @org.junit.Test
    public void writeWithMultipleSheelDiffrent() {

        List listData = new ArrayList<>();
        // sheet1
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            TableHeaderExcelProperty tableHeaderExcelProperty = new TableHeaderExcelProperty();
            tableHeaderExcelProperty.setName("shenke" + i);
            tableHeaderExcelProperty.setAge(29 + i);
            tableHeaderExcelProperty.setSchool("阜阳师范大学" + i);
            list.add(tableHeaderExcelProperty);
        }
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName("个人基本信息");

        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(list);
        multipleSheelPropety.setSheet(sheet);

        // sheet2
        List listCom = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            TableHeaderExcelPropertyTwo tableHeaderExcelPropertyTwo = new TableHeaderExcelPropertyTwo();
            tableHeaderExcelPropertyTwo.setName("shenke" + i);
            tableHeaderExcelPropertyTwo.setCompany("法本" + i);
            tableHeaderExcelPropertyTwo.setSalary("100" + i);
            listCom.add(tableHeaderExcelPropertyTwo);
        }
        Sheet sheetCom = new Sheet(2, 0);
        sheetCom.setSheetName("个人公司信息");

        ExcelUtil.MultipleSheelPropety multipleSheelPropetyCom = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropetyCom.setData(listCom);
        multipleSheelPropetyCom.setSheet(sheetCom);

        // 封装数据
        listData.add(multipleSheelPropety);
        listData.add(multipleSheelPropetyCom);

        ExcelUtil.writeWithMultipleSheel("D:\\share\\modelSheets.xlsx", listData);
    }


}
 
  

 工具类

package com.anji.allways.business.sales.utils;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.anji.allways.common.excel.easyexcel.utils.ExcelException;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @description:
 * @author: chenmingjian
 * @date: 19-3-18 16:16
 */
@Slf4j
public class ExcelUtil {


    private static Sheet initSheet;

    static {
        initSheet = new Sheet(1, 0);
        initSheet.setSheetName("sheet");
        //设置自适应宽度
        initSheet.setAutoWidth(Boolean.TRUE);
    }

    /**
     * 读取少于1000行数据
     *
     * @param filePath 文件绝对路径
     * @return
     */
    public static List readLessThan1000Row(String filePath) {
        return readLessThan1000RowBySheet(filePath, null);
    }

    /**
     * 读小于1000行数据, 带样式
     * filePath 文件绝对路径
     * initSheet :
     * sheetNo: sheet页码,默认为1
     * headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取
     * clazz: 返回数据List 中Object的类名
     */
    public static List readLessThan1000RowBySheet(String filePath, Sheet sheet) {
        if (!StringUtils.hasText(filePath)) {
            return null;
        }

        sheet = sheet != null ? sheet : initSheet;

        InputStream fileStream = null;
        try {
            fileStream = new FileInputStream(filePath);
            return EasyExcelFactory.read(fileStream, sheet);
        } catch (FileNotFoundException e) {
            log.info("找不到文件或文件路径错误, 文件:{}", filePath);
        } finally {
            try {
                if (fileStream != null) {
                    fileStream.close();
                }
            } catch (IOException e) {
                log.info("excel文件读取失败, 失败原因:{}", e);
            }
        }
        return null;
    }

    /**
     * 读大于1000行数据
     *
     * @param filePath 文件觉得路径
     * @return
     */
    public static List readMoreThan1000Row(String filePath) {
        return readMoreThan1000RowBySheet(filePath, null);
    }

    /**
     * 读大于1000行数据, 带样式
     *
     * @param filePath 文件觉得路径
     * @return
     */
    public static List readMoreThan1000RowBySheet(String filePath, Sheet sheet) {
        if (!StringUtils.hasText(filePath)) {
            return null;
        }

        sheet = sheet != null ? sheet : initSheet;

        InputStream fileStream = null;
        try {
            fileStream = new FileInputStream(filePath);
            ExcelListener excelListener = new ExcelListener();
            EasyExcelFactory.readBySax(fileStream, sheet, excelListener);
            return excelListener.getDatas();
        } catch (FileNotFoundException e) {
            log.error("找不到文件或文件路径错误, 文件:{}", filePath);
        } finally {
            try {
                if (fileStream != null) {
                    fileStream.close();
                }
            } catch (IOException e) {
                log.error("excel文件读取失败, 失败原因:{}", e);
            }
        }
        return null;
    }

    /**
     * 生成excle
     *
     * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
     * @param data     数据源
     * @param head     表头
     */
    public static void writeBySimple(String filePath, List> data, List head) {
        writeSimpleBySheet(filePath, data, head, null);
    }

    /**
     * 生成excle
     *
     * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
     * @param data     数据源
     * @param sheet    excle页面样式
     * @param head     表头
     */
    public static void writeSimpleBySheet(String filePath, List> data, List head, Sheet sheet) {
        sheet = (sheet != null) ? sheet : initSheet;

        if (head != null) {
            List> list = new ArrayList<>();
            head.forEach(h -> list.add(Collections.singletonList(h)));
            sheet.setHead(list);
        }

        OutputStream outputStream = null;
        ExcelWriter writer = null;
        try {
            outputStream = new FileOutputStream(filePath);
            writer = EasyExcelFactory.getWriter(outputStream);
            writer.write1(data, sheet);
        } catch (FileNotFoundException e) {
            log.error("找不到文件或文件路径错误, 文件:{}", filePath);
        } finally {
            try {
                if (writer != null) {
                    writer.finish();
                }

                if (outputStream != null) {
                    outputStream.close();
                }

            } catch (IOException e) {
                log.error("excel文件导出失败, 失败原因:{}", e);
            }
        }

    }

    /**
     * 生成excle
     *
     * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
     * @param data     数据源
     */
    public static void writeWithTemplate(String filePath, List data) {
        writeWithTemplateAndSheet(filePath, data, null);
    }

    /**
     * 生成excle
     *
     * @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
     * @param data     数据源
     * @param sheet    excle页面样式
     */
    public static void writeWithTemplateAndSheet(String filePath, List data, Sheet sheet) {
        if (CollectionUtils.isEmpty(data)) {
            return;
        }

        sheet = (sheet != null) ? sheet : initSheet;
        sheet.setClazz(data.get(0).getClass());

        OutputStream outputStream = null;
        ExcelWriter writer = null;
        try {
            outputStream = new FileOutputStream(filePath);
            writer = EasyExcelFactory.getWriter(outputStream);
            writer.write(data, sheet);
        } catch (FileNotFoundException e) {
            log.error("找不到文件或文件路径错误, 文件:{}", filePath);
        } finally {
            try {
                if (writer != null) {
                    writer.finish();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("excel文件导出失败, 失败原因:{}", e);
            }
        }

    }

    /**
     * 生成多Sheet的excle
     *
     * @param filePath              绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx
     * @param multipleSheelPropetys
     */
    public static void writeWithMultipleSheel(String filePath, List multipleSheelPropetys) {
        if (CollectionUtils.isEmpty(multipleSheelPropetys)) {
            return;
        }

        OutputStream outputStream = null;
        ExcelWriter writer = null;
        try {
            outputStream = new FileOutputStream(filePath);
            writer = EasyExcelFactory.getWriter(outputStream);
            for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
                Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
                if (!CollectionUtils.isEmpty(multipleSheelPropety.getData())) {
                    sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
                }
                writer.write(multipleSheelPropety.getData(), sheet);
            }

        } catch (FileNotFoundException e) {
            log.error("找不到文件或文件路径错误, 文件:{}", filePath);
        } finally {
            try {
                if (writer != null) {
                    writer.finish();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("excel文件导出失败, 失败原因:{}", e);
            }
        }

    }

    /**
     * 导出文件路径改造,不只是在某个文件夹下
     *
     * @param fileName 文件名
     * @param multipleSheelPropetys
     * @param response
     */
    public static void writeWithMultipleSheel(String fileName, List multipleSheelPropetys, HttpServletResponse response) {
        if (CollectionUtils.isEmpty(multipleSheelPropetys)) {
            return;
        }

        OutputStream outputStream = null;
        ExcelWriter writer = null;

        try {
            outputStream = getOutputStream(fileName, response);
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
            for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
                Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
                if (!CollectionUtils.isEmpty(multipleSheelPropety.getData())) {
                    sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
                }
                writer.write(multipleSheelPropety.getData(), sheet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.finish();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("excel文件导出失败, 失败原因:{}", e);
            }
        }

    }

    /**
     * 导出文件时为Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        //创建本地文件
        String filePath = fileName + ".xlsx";
        File dbfFile = new File(filePath);
        try {
            if (!dbfFile.exists() || dbfFile.isDirectory()) {
                dbfFile.createNewFile();
            }
            fileName = new String(filePath.getBytes(), "ISO-8859-1");
            response.addHeader("Content-Disposition", "filename=" + fileName);
            return response.getOutputStream();
        } catch (IOException e) {
            throw new ExcelException("创建文件失败!");
        }
    }



    /*********************匿名内部类开始,可以提取出去******************************/

    @Data
    public static class MultipleSheelPropety {

        private List data;

        private Sheet sheet;
    }

    /**
     * 解析监听器,
     * 每解析一行会回调invoke()方法。
     * 整个excel解析结束会执行doAfterAllAnalysed()方法
     *
     * @author: chenmingjian
     * @date: 19-4-3 14:11
     */
    @Getter
    @Setter
    public static class ExcelListener extends AnalysisEventListener {

        private List datas = new ArrayList<>();

        /**
         * 逐行解析
         * object : 当前行的数据
         */
        @Override
        public void invoke(Object object, AnalysisContext context) {
            //当前行
            // context.getCurrentRowNum()
            if (object != null) {
                datas.add(object);
            }
        }


        /**
         * 解析完所有数据后会调用该方法
         */
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            //解析结束销毁不用的资源
        }

    }

}
 
  

 

你可能感兴趣的:(导入导出)