【EasyPoi】Excel导入导出技术,简单易懂

1. 简介

easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 语言(熟悉的表达式语法),完成以前复杂的写法.

2. 使用EasyPoi

2.1 导入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jmh</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--aop切面依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
            <scope>runtime</scope>
        </dependency>
        <!--EasyPoi依赖-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.30</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!--mybatis自动生成代码插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动-->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.44</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.2 application.yml文件配置

#配置tomcat
server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/zmall?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 1234
    type: com.alibaba.druid.pool.DruidDataSource
  thymeleaf:
    #前缀
    prefix: classpath:/templates/
    #后缀
    suffix: .html
    # 模板格式
    mode: LEGACYHTML5
    encoding: UTF-8
    servlet:
      content-type: text/html
    cache: false
    check-template-location: true
  #防止循环依赖
  main:
    allow-circular-references: true

#配置mybatis
mybatis:
  #配置SQL映射文件路径
  mapper-locations: classpath:mapper/*.xml
  #配置别名
  type-aliases-package: com.jmh.demo.model
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true
#配置日志输出
logging:
  level:
    com.jmh.demo.mapper: debug
#配置分页插件
pagehelper:
  reasonable: true
  supportMethodsArguments: true
  page-size-zero: true
  helper-dialect: mysql

2.3 ExcelController核心业务代码

package com.jmh.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.jmh.demo.model.User;
import com.jmh.demo.service.IUserService;
import com.jmh.demo.utils.PageBean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 蒋明辉
 * @data 2023/2/16 22:27
 */
@Controller
@Slf4j
public class ExcelController {


    @Autowired
    private IUserService userService;

    /**
     * 去主页并查询信息绑定
     * @param request 请求
     * @return mv模型
     */
    @RequestMapping("index.html")
    public ModelAndView gotoIndex(HttpServletRequest request){
        //实例模型
        ModelAndView mv=new ModelAndView("index");
        //实例分页对象
        PageBean pageBean=new PageBean();
        pageBean.setRequest(request);
        //获取用户数据并存入模型中
        mv.addObject("users",userService.getUserInfo());
        return mv;
    }

    /**
     * 简单的异常处理
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler
    @ResponseBody
    public String exception(Exception e){
        e.printStackTrace();
        return e.getMessage();
    }

    /**
     * 导入文件
     * @param file 文件
     * @return 结果
     * @throws Exception 异常
     */
    @RequestMapping("/importExcel")
    public String importExcel(MultipartFile file) throws Exception {
        //判断上传文件是否为空
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        //判断格式是否错误
        String xls="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        String xlsx="application/vnd.ms-excel";
        if (!xls.equals(file.getContentType())&&!xlsx.equals(file.getContentType())){
            throw new RuntimeException("上传文件格式错误");
        }
        log.info("文件类型:{}",file.getContentType());
        log.info("file is: {}", file.getOriginalFilename());
        log.info("file is address: {}", file.getInputStream());
        //设置导入对象
        ImportParams importParams = new ImportParams();
        //读取第几个sheet
        importParams.setStartSheetIndex(0);
        //每次读取几个sheet
        importParams.setSheetNum(1);
        //标题占几行
        importParams.setTitleRows(1);
        //头部占几行
        importParams.setHeadRows(1);
        //效验导入字段
        importParams.setImportFields(new String[]{"登录账号"});
        //生成导入execl对象
        List<User> users = ExcelImportUtil.importExcel(file.getInputStream(),
                User.class, importParams);
        //批量增加
        userService.addUserInfoList(new User(users));
        return "redirect:/index.html"; // 上传完成后,跳转到查询所有的方法路径上
    }

    /**
     * 导出文件
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 查询所有数据(要导出的数据)
        List<User> users = userService.getUserInfo();
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("用户列表", "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xls");
        // 生成导出excel对象
        ExportParams exportParams = new ExportParams();
        //设置excel内容标题
        exportParams.setTitle("员工信息");
        //开始导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, users);
        workbook.write(response.getOutputStream());
        //关闭导出
        workbook.close();
        log.info("导出的数据信息:{}", users);
        log.info("浏览器的地址:{}",response.getOutputStream());
    }


}

2.4 前端 index.html页面

<!DOCTYPE html>
<!--suppress ThymeleafVariablesResolveInspection -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<div class="container-fluid">
    <div>
        <div class="col-md-12">
            <h1>选择Excel文件导入/导出</h1>
            <form action="" th:action="@{/importExcel}" method="post"
                  enctype="multipart/form-data" class="form-inline">
                <div class="form-group">
                    <input
                     accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                     type="file" name="file" multiple="multiple"/>
                    <input type="submit" class="btn btn-danger" value="导入"/>
                    <a th:href="@{/exportExcel}" class="btn btn-info">导出excel</a>
                </div>
            </form>
        </div>

        <div>
            <h1>显示导入的数据列表</h1>
            <!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入,遍历被修饰的元素-->
            <table border="1px" th:width="2000px">
                <thead>
                <tr>
                    <td>编号</td>
                    <td>登录账号</td>
                    <td>用户昵称</td>
                    <td>登录密码</td>
                    <td>性别</td>
                    <td>身份证</td>
                    <td>邮箱</td>
                    <td>手机号</td>
                    <td>类型</td>
                </tr>
                <tbody>
            <tr th:each="user:${users}">
                <td th:text="${user.id}"></td>
                <td th:text="${user.loginname}"></td>
                <td th:text="${user.username}"></td>
                <td th:text="${user.password}"></td>
                <td th:text="${user.sex}"></td>
                <td th:text="${user.identitycode}"></td>
                <td th:text="${user.email}"></td>
                <td th:text="${user.mobile}"></td>
                <td th:text="${user.type}"></td>
            </tr>
                </tbody>
                </thead>
            </table>
            <hr/>

        </div>
    </div>
</div>
</body>
</html>

2.5 效果

  • 导入

  • 导出 

 

 


不要把别人想的太好,也不要把别人想的太坏。

猜你喜欢

转载自blog.csdn.net/m0_63300795/article/details/129094756
今日推荐