最近项目中需要用到Excel表格的上传下载功能,于是选择了EasyExcel这款工具,总的来说非常的好用,下面就做一个简单的演示。

官方文档地址

  • https://www.yuque/easyexcel/doc/easyexcel
  • https://alibaba-easyexcel.github.io/

一、依赖

pom.xml 中需要添加的依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>

二、创建User实体类

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    private static final long serialVersionUID = -5144055068797033748L;
    /**
     * 编号
     */
    @ExcelProperty(value = "id", index = 0)
    private Long id;
    /**
     * 用户名
     */
    @ExcelProperty(value = "用户名", index = 1)
    private String username;
    /**
     * 显示名称
     */
    @ExcelProperty(value = "名称", index = 2)
    private String nickname;
    /**
     * 密码
     */
    @ExcelProperty(value = "密码", index = 3)
    private String password;
    /**
     * 邮箱
     */
    @ExcelProperty(value = "邮箱", index = 4)
    private String email;
    /**
     * 头像
     */
    @ExcelProperty(value = "头像", index = 5)
    private String avater;

}

这里我用的是 lombok 生成 getter/setter 和构造器,用的是 Mybatis作为 ORM 框架。
这里用到了 @ExcelProperty 注解,这个注解很重要必要的一个注解,注解中的两个参数value,index分别代表列名,列序号
1.value 通过标题文本对应
2.index 通过文本行号对应

二、Excel导出工具类

public class ExcelUtil {
    /**
     * 导出
     * @param response
     * @param data
     * @param fileName
     * @param sheetName
     * @param clazz
     * @throws Exception
     */
    public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class clazz) throws Exception {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        EasyExcel.write(getOutputStream(fileName, response), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data);
    }
    
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        return response.getOutputStream();
    }
}

三、模板下载

模板下载其实和导出的意思差不多,只不过数据使我们手写的模板数据,而非真实数据。

	/**
     * 下载Excel模板
     */
    @GetMapping("/excel/template")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入用户模板";
        String sheetName = "导入用户模板";
        List<User> userList = new ArrayList<>();
        userList.add(new User(1L, "张三", "zhsngsan", "123456", "847064370@qq", "123"));
        userList.add(new User(2L, "李四", "lisi", "123456", "666666@qq", "456"));
        try {
            ExcelUtil.writeExcel(response, userList, fileName, sheetName, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

代码执行效果图 (其中表格的长度宽度可以在User实体类中添加注解自己设置)

四、导出数据

查询所有用户的信息,然后写入 excel,通过输出流给浏览器。

@GetMapping("/excel/export")
    public void exportData(HttpServletResponse response) {
        String fileName = "用户列表";
        String sheetName = "用户列表";
        List<User> userList = userService.findAll();
        List<User> userExcelList = new ArrayList<>();
        for (User user : userList) {
            User userExcel = User.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .password(user.getPassword())
                    .nickname(user.getNickname())
                    .email(user.getEmail())
                    .avater(user.getAvater()).build();
            userExcelList.add(userExcel);
        }
        try {
            ExcelUtil.writeExcel(response, userExcelList, fileName, sheetName, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

五、导入数据

主要是读取excel中的数据,然后入库。 这里导入都是用同步的,就是全部读取后再做写入操作。 如果需要异步那种,导入几条入库几条可以参考官网文档。

	/**
     * 导入:同步读,单sheet
     */
    @PostMapping("/excel/import")
    public void importData(MultipartFile file) throws Exception {
        List<User> userExcelList = null;
        // 1.excel同步读取数据
        try {
            userExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(User.class).sheet().doReadSync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 2.检查是否大于1000条
        if (userExcelList.size() > 2) {
            throw new RuntimeException("超过最多处理条数");
        }
        // 3.将 userExcelList 转成 userList
        List<User> userList = userExcelList2UserList(userExcelList);
        // 5.入库操作
        userService.insert(userList);
    }

    /**
     * userExcelList转成userList
     *
     * @param userExcelList
     * @return
     */
    private List<User> userExcelList2UserList(List<User> userExcelList) throws ParseException {
        //Date now = new Date();
        List<User> userList = new ArrayList<>();
        for (User userExcel : userExcelList) {
            User user = User.builder()
                    .id(userExcel.getId())
                    .username(userExcel.getUsername())
                    .password(userExcel.getPassword())
                    .nickname(userExcel.getNickname())
                    .email(userExcel.getEmail())
                    .avater(userExcel.getAvater()).build();
            userList.add(user);
        }
        return userList;
    }

用Postman进行导入测试

这样EasyExcel的基本使用就完成了,模板下载,导入导出数据。


UserMapper.xml的对数据库进行操作的语句

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN" "http://mybatis/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.dao.UserMapper">

    <insert id="insert" parameterType="java.util.List">
        insert into user(id, username, nickname, password, email, avater)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id},#{item.username},#{item.nickname},#{item.password},#{item.email},#{item.avater})
        </foreach>
    </insert>


    <select id="findAll" resultType="com.zhang.entity.User">
        select id, username, nickname, password, email, avater
        from user
    </select>
</mapper>


更多推荐

使用EasyExcel实现模板下载、导入和导出功能