easypoi结合MySQL导入_Springboot+EasyPOI+Mybatis 进行对MySQL数据库内表进行导入导出

Springboot+EasyPOI+Mybatis 进行对MySQL数据库内表进行导入导出

最近写功能用到导入导出,在网上发现easypoi,非常好用,个人感觉非常适合中小型项目的使用。

首先感谢 easypoi官方教程

还有俩位大佬的技术支持

https://www.jianshu.com/p/b49459fe3c06

https://www.jianshu.com/p/5d67fb720ece

个人感觉easypoi不像poi代码量那么大,非常轻巧,可以快速上手的api

好了,废话不多说实战and代码

导包 配置pom.xml

cn.afterturn

easypoi-base

3.0.3

cn.afterturn

easypoi-web

3.0.3

cn.afterturn

easypoi-annotation

3.0.3

还有一个jar包是我lib里面放着的,这里注意一下,如果版本是3.3.1的话会进行报错,具体原因我也很懵,之前我用3.3.1启动springboot就报错,后来解决错误时,是因为这个jar包版本太低导致,所以我强烈推荐用3.3.9版本的包

a2bc2aeeeaf10bc37a67b90c7c2571b7.png

工具类 WebExcelUtil

这个工具类我借鉴了大佬们的工具类,在此感谢上面的大佬

import java.io.File;

import java.io.IOException;

import java.net.URLEncoder;

import java.util.List;

import java.util.Map;

import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import org.apache.poi.ss.usermodel.Workbook;

import org.springframework.web.multipart.MultipartFile;

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 cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**

*

* @ClassName: WebExcelUtil.java

* @Description: EasyPOI Excel 导入导出工具类

* @author ajia

*

*/

public class WebExcelUtil {

public static void exportExcel(List> list, String title, String sheetName, Class> pojoClass, String fileName,

boolean isCreateHeader, HttpServletResponse response) throws Exception {

ExportParams exportParams = new ExportParams(title, sheetName);

exportParams.setCreateHeadRows(isCreateHeader);

defaultExport(list, pojoClass, fileName, response, exportParams);

}

/**

*

* @Title: exportExcel

* @Description: 常用导出

* @return void

*/

public static void exportExcel(List> list, String title, String sheetName, Class> pojoClass, String fileName,

HttpServletResponse response) {

try {

defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void exportExcel(List> list, String fileName, HttpServletResponse response) {

try {

defaultExport(list, fileName, response);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

*

* @Title: defaultExport

* @Description: 默认导出

* @return void

*/

private static void defaultExport(List> list, Class> pojoClass, String fileName, HttpServletResponse response,

ExportParams exportParams) throws Exception {

Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);

if (workbook != null)

;

downLoadExcel(fileName, response, workbook);

}

/**

*

* @Title: downLoadExcel

* @Description: 下载excel

* @return void

*/

private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)

throws Exception {

try {

response.setCharacterEncoding("UTF-8");

response.setHeader("content-Type", "application/vnd.ms-excel");

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

workbook.write(response.getOutputStream());

} catch (IOException e) {

throw new Exception(e.getMessage());

}

}

private static void defaultExport(List> list, String fileName, HttpServletResponse response)

throws Exception {

Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);

if (workbook != null)

;

downLoadExcel(fileName, response, workbook);

}

public static ListimportExcel(String filePath, Integer titleRows, Integer headerRows, ClasspojoClass)

throws Exception {

if (StringUtils.isBlank(filePath)) {

return null;

}

ImportParams params = new ImportParams();

params.setTitleRows(titleRows);

params.setHeadRows(headerRows);

Listlist = null;

try {

list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);

} catch (NoSuchElementException e) {

throw new Exception("模板不能为空");

} catch (Exception e) {

e.printStackTrace();

throw new Exception(e.getMessage());

}

return list;

}

public static ListimportExcel(MultipartFile file, Integer titleRows, Integer headerRows, ClasspojoClass)

throws Exception {

if (file == null) {

return null;

}

ImportParams params = new ImportParams();

params.setTitleRows(titleRows);

params.setHeadRows(headerRows);

Listlist = null;

try {

list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);

} catch (NoSuchElementException e) {

throw new Exception("excel文件不能为空");

} catch (Exception e) {

throw new Exception(e.getMessage());

}

return list;

}

}

这个没有太多描述的感兴趣的去easypoi官网研究,开源代码

首先我们先写导出功能

Controller 编写

@PostMapping("/cfq/export")

public void export(HttpServletResponse response) {

Listlist = cfqservice.list();

logger.info("----/cfq/export---导出----");

WebExcelUtil.exportExcel(list, "设备表", "sheet1", IotCfq.class, "cfqtable.xls", response);

}

你没看错就俩行代码直接导出,其中调了一个list查询方法,对表内数据的查询方法。

Service and Serviceimp

Service 的一个接口 提示IotCfq是我对应数据库表内的实体类

Listlist();

@Override

public Listlist() {

return cfqmapper.list();

}

这里写了一个测试的所有没那么多业务代码

mapper and mapper.xml

Listlist();

da4b91241d9e95be41526bda13f12d7b.png

需要注意的是实体类

首先你必须的有个空构造函数

然后每一个实例类上面写注解

@Excel(name = "设备编号", width = 25,orderNum = "0")

private String sebbh;

name是导入或者导出Excel对应的列名,width是Excel表列宽

这个可以去官方文档进行看,easypoi的核心就在这个注解上

以上就是导出的内容。

接下来进行写导入

工具类不变直接写controller

@PostMapping("/cfq/import")

public void upload(MultipartFile file, HttpServletRequest request) throws Exception {

ImportParams params = new ImportParams();

params.setTitleRows(0);

params.setHeadRows(1);

Listlist;

try {

// excel的数据

list = WebExcelUtil.importExcel(file, 1, 1, IotCfq.class);

/*这里是定义中循环遍历的方式,我觉得太麻烦就用了第二种

* for (int i = 0; i < list.size(); i++) { IotCfq cfq = new IotCfq();

* cfq.setSebbh(list.get(i).getSebbh()); cfq.setBjfs(list.get(i).getBjfs());

* cfq.setCfqtype(list.get(i).getCfqtype());

* cfq.setCuftj(list.get(i).getCuftj()); cfq.setMinc(list.get(i).getMinc());

* cfq.setUpdatetime(new Date()); cfq.setCfqzt(list.get(i).getCfqzt());

* cfq.setFzid(list.get(i).getFzid());

*

* // cfqservice.add(cfq); }

*/

for (IotCfq icq : list) {

IotCfq cfq = new IotCfq();

cfq.setSebbh(icq.getSebbh());

cfq.setBjfs(icq.getBjfs());

cfq.setCfqtype(icq.getCfqtype());

cfq.setCuftj(icq.getCuftj());

cfq.setMinc(icq.getMinc());

cfq.setUpdatetime(new Date());

cfq.setCfqzt(icq.getCfqzt());

cfq.setFzid(icq.getFzid());

cfqservice.add(cfq);//调用了一个新增的方法

}

logger.info("---/cfq/import---导入---");

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

导入就是将excel表内数据存储的数据库,无非就是遍历存储,这里调用可一个存储的方法add,其余只要细心无太大问题。尤其注意实体类上不想让其导入导出的字段,不用打、@Excel 就行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是SpringBoot+Mybatis-plus整合easyExcel批量导入Excel到数据库+导出Excel的方法。 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <!-- easyExcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.6</version> </dependency> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> ``` 2. 创建实体类 创建一个实体类,用于映射 Excel 表格中的数据。 ```java @Data public class User { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private Integer age; @ExcelProperty("性别") private String gender; } ``` 3. 创建Excel读取器 创建一个 Excel 读取器,用于读取 Excel 表格中的数据,并将数据存储到数据库中。 ```java @Component public class ExcelReader { @Autowired private UserService userService; /** * 读取 Excel 表格中的数据,并将数据存储到数据库中 */ public void readExcel(String fileName) { EasyExcel.read(fileName, User.class, new UserExcelListener()).sheet().doRead(); } /** * 用户Excel监听器 */ private class UserExcelListener extends AnalysisEventListener<User> { /** * 每读取一行数据,就会调用该方法 */ @Override public void invoke(User user, AnalysisContext context) { userService.save(user); } /** * 读取完整个 Excel 表格后,会调用该方法 */ @Override public void doAfterAllAnalysed(AnalysisContext context) { // do nothing } } } ``` 4. 创建Excel导出器 创建一个 Excel 导出器,用于从数据库中获取数据,并将数据导出到 Excel 表格中。 ```java @Component public class ExcelWriter { @Autowired private UserService userService; /** * 将用户数据导出到 Excel 表格中 */ public void writeExcel(String fileName) { List<User> userList = userService.list(); EasyExcel.write(fileName, User.class).sheet().doWrite(userList); } } ``` 5. 创建Controller 创建一个 Controller,用于接收前端请求,并调用相应的方法处理请求。 ```java @RestController @RequestMapping("/user") public class UserController { @Autowired private ExcelReader excelReader; @Autowired private ExcelWriter excelWriter; /** * 批量导入用户数据 */ @PostMapping("/import") public void importExcel(@RequestParam("file") MultipartFile file) throws IOException { excelReader.readExcel(file.getInputStream()); } /** * 导出用户数据到Excel */ @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { String fileName = "用户信息.xlsx"; response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/vnd.ms-excel"); excelWriter.writeExcel(response.getOutputStream()); } } ``` 6. 配置文件 在 application.yml 文件中添加数据库连接信息。 ```yaml spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root mybatis-plus: mapper-locations: classpath:/mapper/*.xml type-aliases-package: com.example.demo.domain ``` 7. 测试 启动应用程序,并在浏览器中访问以下地址: - http://localhost:8080/user/export :导出 Excel 表格 - http://localhost:8080/user/import :导入 Excel 表格 以上就是 SpringBoot+Mybatis-plus整合easyExcel批量导入Excel到数据库+导出Excel 的方法了,希望能帮到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值