EasyPOI导入导出

操作办公软件分:03   07

JXL:只支持excel,内存优化

POI:功能强大,支持广泛

目录

1.POI的基本使用

1.导包

2.创建excel文件

3.读取excel

2.导出

1.导包(注意冲突)

2.添加注解

3.添加导出按钮

4.控制层进行导出

5.配置视图解析器--->优先执行

3.导入

1.准备页面--->enctype="multipart/form-data"

2.提供一个方法--->根据部门名称拿到部门

  3.准备Controller

4.准备相应的验证功能

    1.导包JSR303

   2.添加注解

   3.完成验证

5.自定义验证

    1.准备验证工具类---实现IExcelVerifyHandler接口

   2.扫描它,交给Spring管理---->方便注入

   3.开启验证


1.POI的基本使用

1.导包

   

    org.apache.poi

    poi

    3.11

    org.apache.poi

    poi-ooxml

    3.11

2.创建excel文件

   //创建一个新的excel,并且写99乘法表:导出

@Test

public void testCreateExcel() throws Exception{

    //1.创建一个工作薄(在内存中)

    SXSSFWorkbook wb = new SXSSFWorkbook();

    //2.创建一张表格

    Sheet sheet = wb.createSheet("99乘法表");

    //3.在表格创建行

    for(int i=1;i<=9;i++){

        Row row = sheet.createRow(i-1);

        //4.在表格中创建列(格子)

        for(int j=1;j<=i;j++){

            Cell cell = row.createCell(j-1);

            //5.格子中写东西

            cell.setCellValue(i+"*"+j+"="+(i*j));

        }

    }

    FileOutputStream out = new FileOutputStream("99.xlsx");

    wb.write(out);

    out.close();

}

 

3.读取excel

   //读取excel:导入

@Test

public void testReadExcel() throws Exception{

    //读取了emp-poi.xlsx ,创建了Workbook(内存)

    InputStream inp = new FileInputStream("emp-poi.xlsx");

    Workbook wb = WorkbookFactory.create(inp);

    //拿到对应的表

    Sheet sheet = wb.getSheetAt(0);

    //拿到这表的总行数

    int lastRowNum = sheet.getLastRowNum();

    for (int i = 1; i <= lastRowNum; i++) {

        //拿到每一行

        Row row = sheet.getRow(i);

        //拿到这一行的总列数

        short lastCellNum = row.getLastCellNum();

        for (int j = 0; j < lastCellNum; j++) {

            //拿到这一个格子与它的数据

            Cell cell = row.getCell(j);

            System.out.print(cell.getStringCellValue()+" ");

        }

        System.out.println();

    }

 

}

 

2.导出

1.导包(注意冲突)

   特别注意:把之前咱们的POI引入去掉(有冲突)

  cn.afterturn

  easypoi-base

  3.2.0

  cn.afterturn

  easypoi-web

  3.2.0

  cn.afterturn

  easypoi-annotation

  3.2.0

2.添加注解

  POIEmployee

@ExcelTarget("emp")

public class PoiEmployee {

    @Excel(name = "名称")

    private String name;

    @Excel(name="邮件",width = 25)

    private String email;

    @Excel(name="年龄")

    private Integer age;

    @Excel(name="性别",replace = {"男_true","女_false"})

    private Boolean sex;

    @Excel(name="出生日期",format = "yyyy-MM-dd")

    private Date bornDate = new Date();

    //type=2:代表这是一张图片

    @Excel(name = "头像",type = 2,height = 25)

    private String headImage;

    @ExcelEntity

    private PoiDepartment department;

 

    // 不要忘了加上getter,setter

}

POIDepartment

@ExcelTarget("dept")public class PoiDepartment {

 

    @Excel(name="部门名称_emp,名称_dept")

    private String name;

 

    @Excel(name="部门地址_emp,地址_dept")

    private String address;

 

    @Excel(name="邮件_dept")

    private String email;

 

    // 不要忘了加上getter,setter

}

 

3.添加导出按钮

  注意:连带高级查询导出

   


    
action="/employee/download" method="post">
        用户名:
        邮件:
        部门 :                 data-options="valueField:'id',textField:'name',panelHeight:'auto',url:'/util/departmentList',editable:false">
        查找
        
        
    

 

4.控制层进行导出

  //POI导出
@RequestMapping("/download")
public String download(ModelMap map, EmployeeQuery query, HttpServletRequest request) {
    //拿到所有数据
    List list = employeeServie.findByQuery(query);
    //获取到真实路径
   //解决了下载的图片的路径问题
    String realPath = request.getServletContext().getRealPath("");
    list.forEach(e -> {
        e.setHeadImage(realPath+e.getHeadImage());
        System.out.println(e.getHeadImage());
    });

    //设置一些属性
    ExportParams params = new ExportParams("员工管理", "明细", ExcelType.XSSF);
    //params.setFreezeCol(3);
    map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
    map.put(NormalExcelConstants.CLASS, Employee.class);//导出实体
    map.put(NormalExcelConstants.PARAMS, params);//参数
    map.put(NormalExcelConstants.FILE_NAME, "employee");//文件名称
    //返回的名称 :easypoiExcelView -> 并没有找我的bean,而且当做一个路径去进行访问
    //  现在默认去找的视图解析器,而没有找我的那一个bean
    return NormalExcelConstants.EASYPOI_EXCEL_VIEW;//View名称
}

5.配置视图解析器--->优先执行

  



      p:order="0" />

 

3.导入

1.准备页面--->enctype="multipart/form-data"

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title
    <%@include file="/WEB-INF/views/head.jsp" %>



enctype="multipart/form-data">
    name="empFile" style="width:80%"
           data-options="prompt:'选择一个文件...',buttonText: '选择文件'" />
    


2.提供一个方法--->根据部门名称拿到部门

  1. Department findByName(String name);---->repository
  2. Department findByName(String name);---->接口

     3. public Department findByName(String name) {
           return departmentRepository.findByName(name);}--->实现

  3.准备Controller

       @RequestMapping("/employeeXlsx")

public String employeeXlsx(MultipartFile empFile) throws Exception {

 

    //准备导入的参数

    ImportParams params = new ImportParams();

    params.setTitleRows(1);

 

    List list = ExcelImportUtil.importExcel(

            empFile.getInputStream(),

            Employee.class,

            params);

 

    list.forEach(e ->{

       // System.out.println(e+","+e.getDepartment());

        //根据部门名称拿到它的部门,再放到对应的员工中

        Department dept = departmentService.findByName(e.getDepartment().getName());

        e.setDepartment(dept);

        //给一个默认密码

        e.setPassword("123");

        employeeService.save(e);

    });

 

    return "import";

}

4.准备相应的验证功能

    1.导包JSR303

   

  org.hibernate
  hibernate-validator
  5.2.4.Final

 2.添加注解

     不能为空@NotNull

     外键@ExcelEntity

     年龄@Max(value = 80,message = "年龄不能大于80")

   3.完成验证

  //上传员工excel的功能
@RequestMapping("/employeeXlsx")
public String employeeXlsx(MultipartFile empFile, HttpServletResponse response) throws Exception{
    //设置导入的参数
    ImportParams params = new ImportParams();
    //params.setTitleRows(1);
    params.setNeedVerfiy(true); //代表这里是需要验证的
    params.setHeadRows(1);
  
    ExcelImportResult result = ExcelImportUtil.importExcelMore(
            empFile.getInputStream(),
            Employee.class, params);
    //拿到正确的数据,然后把它们保存到数据库
    List list = result.getList();
    list.forEach(e ->{
        //从数据库中查询部门
        String deptName = e.getDepartment().getName();
        Department dept = departmentService.findByName(deptName);
        e.setDepartment(dept);
        //设置初始密码
        e.setPassword("123");
        employeeService.save(e);
    });

    Workbook failWorkbook = result.getFailWorkbook();
    //结合以前我们学习的下载功能把文件写出去
    //下面设置好直接使用即可导出
    //设置响应的文件类型 mime类型
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    //attachment:不要用浏览器打开(下载)
    response.setHeader("Content-disposition", "attachment;filename=empFail.xlsx");
    response.setHeader("Pragma", "No-cache");//设置不要缓存
    OutputStream ouputStream = response.getOutputStream();
    failWorkbook.write(ouputStream);
    ouputStream.flush();
    ouputStream.close();
    return "import";
}

5.自定义验证

    1.准备验证工具类---实现IExcelVerifyHandler接口

 //自定义验证
@Component
public class EmployeeExcelVerifyHandler implements IExcelVerifyHandler {

    @Autowired
    private IEmployeeService employeeService;

    @Override
    public ExcelVerifyHandlerResult verifyHandler(Employee employee) {
        ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult(true);
        //如果存在,返回false
        if(!employeeService.checkUsername(employee.getUsername())){
            //代表用户名重复
            result.setMsg("用户名重复了");
            result.setSuccess(false);
        }
        return result;
    }
}

   2.扫描它,交给Spring管理---->方便注入

  




      p:order="0" />

 

   3.开启验证

   @Controller
@RequestMapping("/import")
public class ImprotController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private EmployeeExcelVerifyHandler employeeExcelVerifyHandler;


    @RequestMapping("/index")
    public String index() {
        return "import";
    }

    //上传员工excel的功能
    @RequestMapping("/employeeXlsx")
    public String employeeXlsx(MultipartFile empFile, HttpServletResponse response) throws Exception{
        //设置导入的参数
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);
        params.setNeedVerfiy(true); //代表这里是需要验证的
        params.setHeadRows(1);
        //加入自定义验证
        params.setVerifyHandler(employeeExcelVerifyHandler);

        ExcelImportResult result = ExcelImportUtil.importExcelMore(
                empFile.getInputStream(),
                Employee.class, params);
        //拿到正确的数据,然后把它们保存到数据库
        List list = result.getList();
        list.forEach(e ->{
            //从数据库中查询部门
            String deptName = e.getDepartment().getName();
            Department dept = departmentService.findByName(deptName);
            e.setDepartment(dept);
            //设置初始密码
            e.setPassword("123");
            employeeService.save(e);
        });

        Workbook failWorkbook = result.getFailWorkbook();
        //结合以前我们学习的下载功能把文件写出去
        //下面设置好直接使用即可导出
        //设置响应的文件类型 mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //attachment:不要用浏览器打开(下载)
        response.setHeader("Content-disposition", "attachment;filename=empFail.xlsx");
        response.setHeader("Pragma", "No-cache");//设置不要缓存
        OutputStream ouputStream = response.getOutputStream();
        failWorkbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
        return "import";
    }
}

你可能感兴趣的:(EasyPOI)