EasyPOI实战入门

EasyPOI实战入门

  • 入门案例
  • 导出Excel
    • 导出基本数据
    • 一对一关系导出
    • 一对多关系导出
    • 导出图片
    • 大数据量导出
    • 自定义列导出表格
  • 导入Excel
    • 导入基本数据
  • 集成web实现导入导出
    • 1.搭建springboot+mybatis项目环境
      • 1.创建springboot项目
      • 2.引入相关依赖
      • 3.编写配置文件
      • 4.项目结构
      • 5.数据库创建
      • 项目源码

入门案例

官网介绍
引入相关依赖

 
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-baseartifactId>
            <version>4.1.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-webartifactId>
            <version>4.1.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-annotationartifactId>
            <version>4.1.0version>
        dependency>

导出Excel

导出基本数据

注意:导出Excel的对象必须实现对象序列化接口
1.定义对象

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
@ExcelTarget("employee")//导出表格的唯一标识,可以不写
public class Employee implements Serializable {
    /*
        @Excel(name="表格列标题")
        orderNum:列的排序
        exportFormat:导出的时间格式,以这个是否为空来判断是否需要格式化日期
        replace:值的替换
        width:列宽
        suffix:文字后缀
        @ExcelIgnore:添加到实体类属性上,表示该属性不导出到excel中
     */
    @Excel(name = "编号",orderNum = "1",replace = {"xxx_1","nnn_2"},width = 20)
    private String id;
    @Excel(name = "姓名",orderNum = "2",width = 30)
    private String name;
    @Excel(name = "年龄",orderNum = "4",suffix = "岁",width = 20)
    private Integer age;
    @Excel(name = "生日",exportFormat = "yyyy年MM月dd日",orderNum = "3",width = 20.0)
    private Date bir;
}

package com.example.demo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.demo.entity.Employee;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class TestPOI {
    public List<Employee> getEmployees(){
        List<Employee>employees=new ArrayList<>();
        for (int i=0;i<10;i++){
            Employee employee =new Employee();
            employee.setId(String.valueOf(i+1));
            employee.setAge(20+i);
            employee.setName("张"+i);
            employee.setBir(new Date());
            employees.add(employee);
        }
        return employees;
    }

    /**
     *导出Excel
     */
    @Test
    public void test() throws IOException {
        List<Employee>list = getEmployees();
        //导出Excel
        /*
        参数1:exportParams 导出的配置对象
        参数2: 导出的类型
        参数3:导出数据集合
         */
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("用户列表","用户信息"),Employee.class,list);
        //将excel写入指定位置(employee.xls表格是已经存在的)
        workbook.write(new FileOutputStream("C:\\Users\\16837\\Desktop\\employee.xls"));
    }
}

导出表格内容如下
EasyPOI实战入门_第1张图片

一对一关系导出

1.实体类

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
//@ExcelTarget("employee")//导出表格的唯一标识
public class Employee implements Serializable {
    /*
        @Excel(name="表格列标题")
        orderNum:列的排序
        exportFormat:导出的时间格式,以这个是否为空来判断是否需要格式化日期
        replace:值的替换
        width:列宽
        suffix:文字后缀
        @ExcelIgnore:添加到实体类属性上,表示该属性不导出到excel中
     */
    @Excel(name = "编号",orderNum = "1",replace = {"xxx_1","nnn_2"},width = 20)
    private String id;
    @Excel(name = "姓名",orderNum = "2",width = 30)
    private String name;
    @Excel(name = "年龄",orderNum = "4",suffix = "岁",width = 20)
    private Integer age;
    @Excel(name = "生日",exportFormat = "yyyy年MM月dd日",orderNum = "3",width = 20.0)
    private Date bir;
    @ExcelEntity // 标识一对一关系
    private Card card;
}

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.io.Serializable;

@Data
public class Card implements Serializable {
    @Excel(name="身份证号码",width = 30,orderNum = "5")
    private String no;
    @Excel(name = "籍贯",width = 30,orderNum = "6")
    private String address;

}

测试

package com.example.demo;

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 com.example.demo.entity.Card;
import com.example.demo.entity.Employee;
import com.example.demo.entity.EmployeeVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class TestPOI {
    public List<Employee> getEmployees(){
        List<Employee>employees=new ArrayList<>();
        for (int i=0;i<10;i++){
            Employee employee =new Employee();
            employee.setId(String.valueOf(i+1));
            employee.setAge(20+i);
            Card card =new Card();
            card.setNo("123456789000000");
            card.setAddress("北京市朝阳区");
            employee.setCard(card);
            employee.setName("张"+i);
            employee.setBir(new Date());
            employees.add(employee);
        }
        return employees;
    }

    /**
     *导出Excel
     */
    @Test
    public void test() throws IOException {
        List<Employee>list = getEmployees();
        //导出Excel
        /*
        参数1:exportParams 导出的配置对象
        参数2: 导出的类型
        参数3:导出数据集合
         */
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("用户列表","用户信息"),Employee.class,list);
        //将excel写入指定位置(employee.xls表格是已经存在的)
        workbook.write(new FileOutputStream("C:\\Users\\16837\\Desktop\\employee.xls"));
    }
}

测试结果
EasyPOI实战入门_第2张图片

一对多关系导出

1.实体类

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
//@ExcelTarget("employee")//导出表格的唯一标识
public class Employee implements Serializable {
    /*
        @Excel(name="表格列标题")
        orderNum:列的排序
        exportFormat:导出的时间格式,以这个是否为空来判断是否需要格式化日期
        replace:值的替换
        width:列宽
        suffix:文字后缀
        needMerge:是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row。true为需要合并单元格
        @ExcelIgnore:添加到实体类属性上,表示该属性不导出到excel中
     */
    @Excel(name = "编号",orderNum = "1",replace = {"xxx_1","nnn_2"},width = 20,needMerge = true)
    private String id;
    @Excel(name = "姓名",orderNum = "2",width = 30,needMerge = true)
    private String name;
    @Excel(name = "年龄",orderNum = "4",suffix = "岁",width = 20,needMerge = true)
    private Integer age;
    @Excel(name = "生日",exportFormat = "yyyy年MM月dd日",orderNum = "3",width = 20.0,needMerge = true)
    private Date bir;
    @ExcelEntity // 标识一对一关系
    private Card card;
    @ExcelCollection(name = "订单列表",orderNum = "8")//标识一对多关系
    private List<Order> orderList;
}

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.io.Serializable;

@Data
public class Card implements Serializable {
    @Excel(name="身份证号码",width = 30,orderNum = "5",needMerge = true)
    private String no;
    @Excel(name = "籍贯",width = 30,orderNum = "6",needMerge = true)
    private String address;
}

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

@Data
@AllArgsConstructor
public class Order implements Serializable {
    @Excel(name = "订单编号",orderNum = "7",width = 30)
    private String no;
    @Excel(name = "订单名称",orderNum = "8",width = 30)
    private String name;
}

测试

package com.example.demo;

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 com.example.demo.entity.Card;
import com.example.demo.entity.Employee;
import com.example.demo.entity.EmployeeVo;
import com.example.demo.entity.Order;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class TestPOI {
    public List<Employee> getEmployees(){
        List<Employee>employees=new ArrayList<>();
        for (int i=0;i<10;i++){
            Employee employee =new Employee();
            employee.setId(String.valueOf(i+1));
            employee.setAge(20+i);
            Card card =new Card();
            card.setNo("123456789000000");
            card.setAddress("北京市朝阳区");
            employee.setCard(card);
            List<Order> orderList = new ArrayList<>();
            orderList.add(new Order("11","超短裙"));
            orderList.add(new Order("12","连衣裙"));
            orderList.add(new Order("22","蓬蓬裙"));
            orderList.add(new Order("23","短裙"));
            employee.setOrderList(orderList);
            employee.setName("张"+i);
            employee.setBir(new Date());
            employees.add(employee);
        }
        return employees;
    }

    /**
     *导出Excel
     */
    @Test
    public void test() throws IOException {
        List<Employee>list = getEmployees();
        //导出Excel
        /*
        参数1:exportParams 导出的配置对象
        参数2: 导出的类型
        参数3:导出数据集合
         */
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("用户列表","用户信息"),Employee.class,list);
        //将excel写入指定位置(employee.xls表格是已经存在的)
        workbook.write(new FileOutputStream("C:\\Users\\16837\\Desktop\\employee.xls"));
    }
}

导出表格样式
EasyPOI实战入门_第3张图片

导出图片

  • 往往随着业务不断变化,可能需要在导出excel时将图片信息也一并导出,如商品图标,用户头像信息等数据,这时候easypoi该如何处理呢?

1.实体类设计

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
//@ExcelTarget("employee")//导出表格的唯一标识
public class Employee implements Serializable {
    /*
        @Excel(name="表格列标题")
        orderNum:列的排序
        exportFormat:导出的时间格式,以这个是否为空来判断是否需要格式化日期
        replace:值的替换
        width:列宽
        suffix:文字后缀
        needMerge:是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row。true为需要合并单元格
        @ExcelIgnore:添加到实体类属性上,表示该属性不导出到excel中
     */
    @Excel(name = "头像信息",orderNum = "0",type = 2,width = 30,height = 30,imageType = 1,needMerge = true)//type的值一定要指定为2
    private String photo;//定义头像,直接写指定图片路径
    @Excel(name = "编号",orderNum = "1",replace = {"xxx_1","nnn_2"},width = 20,needMerge = true)
    private String id;
    @Excel(name = "姓名",orderNum = "2",width = 30,needMerge = true)
    private String name;
    @Excel(name = "年龄",orderNum = "4",suffix = "岁",width = 20,needMerge = true)
    private Integer age;
    @Excel(name = "生日",exportFormat = "yyyy年MM月dd日",orderNum = "3",width = 20.0,needMerge = true)
    private Date bir;
    @ExcelEntity // 标识一对一关系
    private Card card;
    @ExcelCollection(name = "订单列表",orderNum = "8")//标识一对多关系
    private List<Order> orderList;
}
package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.io.Serializable;

@Data
public class Card implements Serializable {
    @Excel(name="身份证号码",width = 30,orderNum = "5",needMerge = true)
    private String no;
    @Excel(name = "籍贯",width = 30,orderNum = "6",needMerge = true)
    private String address;
}

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

@Data
@AllArgsConstructor
public class Order implements Serializable {
    @Excel(name = "订单编号",orderNum = "7",width = 30)
    private String no;
    @Excel(name = "订单名称",orderNum = "8",width = 30)
    private String name;
}

2.测试

package com.example.demo;

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 com.example.demo.entity.Card;
import com.example.demo.entity.Employee;
import com.example.demo.entity.EmployeeVo;
import com.example.demo.entity.Order;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class TestPOI {
    public List<Employee> getEmployees(){
        List<Employee>employees=new ArrayList<>();
        for (int i=0;i<10;i++){
            Employee employee =new Employee();
            employee.setId(String.valueOf(i+1));
            employee.setAge(20+i);
            //使用绝对路径
            employee.setPhoto("C:\\Users\\16837\\Desktop\\doc\\1.jpg");
            Card card =new Card();
            card.setNo("123456789000000");
            card.setAddress("北京市朝阳区");
            employee.setCard(card);
            List<Order> orderList = new ArrayList<>();
            orderList.add(new Order("11","超短裙"));
            orderList.add(new Order("12","连衣裙"));
            orderList.add(new Order("22","蓬蓬裙"));
            orderList.add(new Order("23","短裙"));
            employee.setOrderList(orderList);
            employee.setName("张"+i);
            employee.setBir(new Date());
            employees.add(employee);
        }
        return employees;
    }

    /**
     *导出Excel
     */
    @Test
    public void test() throws IOException {
        List<Employee>list = getEmployees();
        //导出Excel
        /*
        参数1:exportParams 导出的配置对象
        参数2: 导出的类型
        参数3:导出数据集合
         */
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("用户列表","用户信息"),Employee.class,list);
        //将excel写入指定位置(employee.xls表格是已经存在的)
        workbook.write(new FileOutputStream("C:\\Users\\16837\\Desktop\\employee.xls"));
    }
}

表格输出内容
EasyPOI实战入门_第4张图片

大数据量导出

大数据导出是当我们的导出数量在几万,到上百万的数据时,一次从数据库查询这么多数据加载到内存然后写入会对我们的内存和CPU都产生压力,这个时候需要我们像分页一样处理导出分段写入Excel缓解Excel的压力

注意:最好大量数据进行分页处理,每次导出数据最好不要超过1w条记录

自定义列导出表格

package com.study.easypoidemo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.study.easypoidemo.entity.Employee;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileOutputStream;
import java.util.*;

@SpringBootTest
class EasypoidemoApplicationTests {
    public List<Employee> getEmployees(){
        List<Employee>employees=new ArrayList<>();
        for (int i=0;i<10;i++){
            Employee employee =new Employee();
            employee.setId(String.valueOf(i+1));
            employee.setAge(20+i);
            employee.setName("张"+i);
            employee.setBir(new Date());
            employees.add(employee);
        }
        return employees;
    }
    @Test
    public void test(){
        try{
            /**动态生成列*/
            List<ExcelExportEntity>exportEntityList=new ArrayList<>();
            ExcelExportEntity entity=null;
            entity=new ExcelExportEntity("姓 名","name",15);
            exportEntityList.add(entity);
            entity=new ExcelExportEntity("年 龄","age",15);
            exportEntityList.add(entity);
            entity=new ExcelExportEntity("1 月","janaray",15);
            exportEntityList.add(entity);
            entity=new ExcelExportEntity("2 月","febray",15);
            exportEntityList.add(entity);
            entity=new ExcelExportEntity("3 月","May",15);
            entity.setSuffix("%");
            exportEntityList.add(entity);
            ExportParams params =new ExportParams();
            params.setSheetName("测试数据");/*设置单元簿的名称*/
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            List<Employee>lists=getEmployees();
            for (int i=0;i<lists.size();i++){
                /*根据key填充表格数据*/
                Map<String, Object> map = new HashMap<>();
                map.put("name",lists.get(i).getName());
                map.put("age",lists.get(i).getAge());
                map.put("janaray",lists.get(i).getBir());
                map.put("May",10);
                list.add(map);
            }
            /**导出表格*/
            Workbook workbook= ExcelExportUtil.exportExcel(params,exportEntityList,list);
            workbook.write(new FileOutputStream("C:\\Users\\16837\\Desktop\\2.xls",true));
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}

输出表格
EasyPOI实战入门_第5张图片

导入Excel

导入基本数据

1准备导入的目标Excel
EasyPOI实战入门_第6张图片
2、定义实体类

package com.example.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
@Data
public class EmployeeVo implements Serializable {
    @Excel(name = "编号")
    private String id;
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄",suffix = "岁")
    private Integer age;
    // importFormat:导入的时间格式,以这个是否为空来判断是否需要格式化日期
    @Excel(name = "生日",importFormat = "yyyy年MM月dd日",format = "yyyy-MM-dd HH:mm:ss")
    private Date bir;
}

3.读取数据

package com.example.demo;

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 com.example.demo.entity.Employee;
import com.example.demo.entity.EmployeeVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class TestPOI {
    /**
     * 导入表格
     */
    @Test
    public void testImport() throws Exception {
        /**
         * 参数1:导入excel文件流,
         * 参数2:导入类型
         * 参数3:导入的配置对象
         */
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题列占几行
        params.setHeadRows(1);//header列占几行
          //params.setImportFields(new String[]{"编号"});//不包含'编号列'提示不是合法的Excel模板
        //        params.setStartSheetIndex(2);//读取指定的sheet,从第二个开始
        List<EmployeeVo>list= ExcelImportUtil.importExcel(new FileInputStream("C:\\Users\\16837\\Desktop\\employee.xls"), EmployeeVo.class,params);
        list.forEach(System.out::println);

    }
}

导入小技巧

  • 读取指定的sheet
    比如要读取上传的的第二个sheet,那么需要把startSheetIndex=1就可以了
  • 读取几个sheet
    比如读取前2个sheet,那么sheetNum=2就可以了
  • 读取第二个到第五个sheet
    设置startSheetIndex=1然后sheetNum=4
  • 读取全部的sheet
    shettNum设置大点就可以了
  • 判断一个Excel是不是合法的Excel
    importFields 设置下值,就是表示表头必须至少包含的字段,如果缺一个就是不合法的excel。

集成web实现导入导出

https://gitee.com/cao_jianhua/easy-poi_-spring-boot/blob/master/src/main/java/com/cjh/controller/UserController.java

1.搭建springboot+mybatis项目环境

1.创建springboot项目

2.引入相关依赖

  <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.3version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.27version>
        dependency>
        <dependency>
            
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.10version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
            <version>2.1.7.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-baseartifactId>
            <version>4.1.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-webartifactId>
            <version>4.1.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-annotationartifactId>
            <version>4.1.0version>
        dependency>


    dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>
  • mybatis
  • mysql
  • druid
  • easypoi
  • thymleaf
  • lombok

3.编写配置文件

#spring.profiles.active=dev
server.port=8989
spring.application.name=easypoi

#关闭thymeleaf缓存
spring.thymeleaf.cache=false

#数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

#mybatis的设置
mybatis.mapper-locations=classpath*:com/demo/mapper/*.xml
mybatis.type-aliases-package=com.demo.entity

#
logging.level.com.cjh.dao = debug

4.项目结构

EasyPOI实战入门_第7张图片

5.数据库创建

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `bir` timestamp(0) NULL DEFAULT NULL,
  `no` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `address` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (2, '机器人0号', '2020-09-14 00:00:00', '522401199708139634', '贵州遵义');
INSERT INTO `t_user` VALUES (3, '机器人1号', '2020-09-15 00:00:00', '522401199708139635', '贵州毕节');
INSERT INTO `t_user` VALUES (4, '机器人2号', '2020-09-16 00:00:00', '522401199708139636', '北京');
INSERT INTO `t_user` VALUES (5, '机器人3号', '2020-09-17 00:00:00', '522401199708139637', '贵州贵阳');
INSERT INTO `t_user` VALUES (6, '机器人4号', '2020-09-18 00:00:00', '522401199708139638', '厦门');

SET FOREIGN_KEY_CHECKS = 1;

项目源码

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>导入excel的主页面title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <h1>选择Excel导入到数据中h1>
                
                <form th:action="@{/user/import}" method="post" class="form-inline" enctype="multipart/form-data">
                    <div class="form-group">
                        <input type="file" class="form-control" name="excelFile">
                        <input type="submit" class="btn btn-danger" value="导入数据">
                    div>
                form>
            div>
            <div class="col-md-12">
                <h1>显示导入数据列表h1>
                <table class="table table-bordered">
                    <tr>
                        <th>编号th>
                        <th>头像th>
                        <th>姓名th>
                        <th>生日th>
                    tr>
                    <tr th:each="user:${users}">
                        <td th:text="${user.id}">1td>
                        <td th:text="${user.name}"> 小陈td>
                        <td th:text="${#dates.format(user.bir,'yyyy-MM-dd')}">23td>
                        <td th:text="${user.no}">td>
                        <td th:text="${user.address}">td>
                    tr>
                table>
                <hr>
                <a th:href="@{/user/export}" class="btn btn-info" >导出excela>
            div>
        div>
    div>
body>
html>
package com.demo.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
@ExcelTarget("user")
public class User implements Serializable {
    @Excel(name = "编号")
    private String id;
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "生日",format = "yyyy年MM月dd日",width = 30.0)
    private Date bir;
    @Excel(name = "身份证号",width = 30.0)
    private String no;
    @Excel(name = "籍贯")
    private String address;
}


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.dao.UserDao">
    <select id="findAll" resultType="User">
        select id,
               name,
               bir, no, address
        from
            t_user
    select>

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        values (#{id}, #{name}, #{bir}, #{no}, #{address})
    insert>
mapper>
package com.demo.dao;

import com.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserDao {
    List<User> findAll();
    void save(User user);
}

package com.demo.service;

import com.demo.entity.User;

import java.util.List;

public interface UserService {
    List<User> findAll();
    void saveAll(List<User> users);
}

package com.demo.service.Impl;

import com.demo.dao.UserDao;
import com.demo.entity.User;
import com.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao dao;
    @Override
    public List<User> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<User> users) {
        for (User user : users) {
            user.setId(null);
            dao.save(user);
        }
    }
}

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

package com.demo.controller;

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 com.demo.entity.User;
import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    UserService userService;
    /**
     * 导出excel
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/export")
    public void ExportExcel(HttpServletResponse response) throws IOException {
        List<User> users = userService.findAll();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户列表信息", "用户信息"), User.class, users);
        // 设置响应头
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("用户列表.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }
    @RequestMapping("/import")
    public String importExcel(MultipartFile excelFile) throws Exception {
//        log.info("文件名:[{}]",excelFile.getOriginalFilename());
        // excel导入
        //excel导入
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);

        List<User> users = ExcelImportUtil.importExcel(excelFile.getInputStream(), User.class, params);
        users.forEach(System.out::println);
        userService.saveAll(users);
        return "redirect:/user/findAll";//上传完成之后,跳转到查询所有信息路径
    }
    /**
     * 查询所有
     *
     * @param model
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        return "index";
    }
}


你可能感兴趣的:(java,java)