springboot集成easyPoi实现excel数据导入到Mysql数据库
时间:2021-08-12
本文章向大家介绍springboot集成easyPoi实现excel数据导入到Mysql数据库,主要包括springboot集成easyPoi实现excel数据导入到Mysql数据库使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
springboot集成easyPoi实现excel数据导入到Mysql数据库
-
easyPoi官方文档:http://easypoi.mydoc.io/
-
通过Mybatis generator生成相关Tbxxx,TbxxxExample,TbxxxMapper.java,TbxxxMapper.xml,TbxxxService
-
引入依赖:
<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.2.0</version> </dependency>
-
注解实体类:
import cn.afterturn.easypoi.excel.annotation.Excel; import com.yun.cloud.base.model.BaseModel; import lombok.Data; import java.io.Serializable; @Data public class TbProductStandard extends BaseModel implements Serializable { private String id; @Excel(name = "code") private String code; @Excel(name = "parent_code") private String parentId; @Excel(name = "type_name") private String typeName; }
相关注解介绍:
@Excel 作用到实体类字段上面,是对Excel一列的一个描述
@ExcelCollection 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示
@ExcelEntity 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段
@ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出
@ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理
————————————————
原文链接:https://blog.csdn.net/weixin_41922289/article/details/100191112- 受注解的excel格式:
-
设置excel导入导出工具类:
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; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; public class ProductExcelUtils { public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) { ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) { defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) { Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); if (workbook != null) ; downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { 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 NormalException(e.getMessage()); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null) ; downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (StringUtils.isBlank(filePath)) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); } catch (NoSuchElementException e) { // throw new NormalException("模板不能为空"); } catch (Exception e) { e.printStackTrace(); // throw new NormalException(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (file == null) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); } catch (NoSuchElementException e) { // throw new NormalException("excel文件不能为空"); } catch (Exception e) { // throw new NormalException(e.getMessage()); System.out.println(e.getMessage()); } return list; } }
-
controller层:
import com.yun.cloud.base.result.Result; import com.yun.cloud.gap.business.ProductStandardBusiness; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/productstandard") public class ProductStandardController { @Autowired private ProductStandardBusiness productStandardBusiness; /** * 导入excel * @param file * @return */ @PostMapping("/importExcel") public Result importExcel(@RequestParam("file") MultipartFile file) { return productStandardBusiness.importExcel(file); } }
-
business层:
import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; import com.alibaba.fastjson.JSONObject; import com.yun.cloud.base.result.Result; import com.yun.cloud.base.utils.IdGenUtil; import com.yun.cloud.gap.model.TbProductStandard; import com.yun.cloud.gap.model.TbProductStandardExample; import com.yun.cloud.gap.service.TbProductStandardService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.List; @Slf4j @Service("ProductStandardBusiness") public class ProductStandardBusiness { @Autowired private TbProductStandardService tbProductStandardService; @Value("${machine}") private int machineId; @Value("${datacenter}") private int dataCenterId; public Result importExcel(MultipartFile file) { ImportParams importParams = new ImportParams(); // 数据处理 importParams.setHeadRows(1); importParams.setTitleRows(1); // 需要验证 importParams.setNeedVerfiy(false); try { ExcelImportResult<TbProductStandard> result = ExcelImportUtil.importExcelMore(file.getInputStream(), TbProductStandard.class, importParams); List<TbProductStandard> tbProductStandardList = result.getList(); for (TbProductStandard tbProductStandard : tbProductStandardList) { log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(tbProductStandard)); //保存到mysql String id = IdGenUtil.getNextId(machineId,dataCenterId); tbProductStandard.setId(id); int i = tbProductStandardService.insertSelective(tbProductStandard); if(i < 1){ log.error("保存失败"); return Result.err("保存失败"); } } log.info("从Excel导入数据一共 {} 行 ", tbProductStandardList.size()); } catch (Exception e) { log.error("导入失败:{}", e.getMessage()); return Result.err("导入失败"); } return Result.suc(); } }
-
测试
原文地址:https://www.cnblogs.com/horseweed/p/15134814.html
- Spring思维导图,让Spring不再难懂(cache篇)
- 曲折的10g,11g中EM的安装配置过程(r4笔记第98天)
- Linux 学习记录 一(安装、基本文件操作).
- 实用的位运算应用(r4笔记第97天)
- 关于date格式的两个案例(r4笔记第96天)
- 【新技术分享】C++17 最新进展
- Ant + Jenkies +Tomcat 自动构建部署Web项目
- 博客项目Tale思维导图,让项目不再难懂
- 关于权限管理的实用脚本(r4笔记第94天)
- Ant学习笔记
- 清理session的小插曲(r4笔记第95天)
- CVE-2017-16943 Exim UAF漏洞分析
- Java泛型学习
- Jenkins修改管理员密码.
- MySQL 教程
- MySQL 安装
- MySQL 管理与配置
- MySQL PHP 语法
- MySQL 连接
- MySQL 创建数据库
- MySQL 删除数据库
- MySQL 选择数据库
- MySQL 数据类型
- MySQL 创建数据表
- MySQL 删除数据表
- MySQL 插入数据
- MySQL 查询数据
- MySQL where 子句
- MySQL UPDATE 查询
- MySQL DELETE 语句
- MySQL LIKE 子句
- mysql order by
- Mysql Join的使用
- MySQL NULL 值处理
- MySQL 正则表达式
- MySQL 事务
- MySQL ALTER命令
- MySQL 索引
- MySQL 临时表
- MySQL 复制表
- 查看MySQL 元数据
- MySQL 序列 AUTO_INCREMENT
- MySQL 处理重复数据
- MySQL 及 SQL 注入
- MySQL 导出数据
- MySQL 导入数据
- MYSQL 函数大全
- MySQL Group By 实例讲解
- MySQL Max()函数实例讲解
- mysql count函数实例
- MYSQL UNION和UNION ALL实例
- MySQL IN 用法
- MySQL between and 实例讲解
- 小白学PyTorch | 18 TF2构建自定义模型
- 扩展之Tensorflow2.0 | 19 TF2模型的存储与载入
- 扩展之Tensorflow2.0 | 20 TF2的eager模式与求导
- Django JSONField SQL注入漏洞(CVE-2019-14234)分析与影响
- 扩展之Tensorflow2.0 | 21 Keras的API详解(上)卷积、激活、初始化、正则
- 持续代码质量管理-SonarQube-7.3部署
- 攻击Scrapyd爬虫
- 【webpack】从vue-cli 2x 到 3x 迁移与实践
- 前端单元测试那些事
- 前端Nginx那些事
- 前端运维部署那些事
- 《前端那些事》从0到1开发简单脚手架
- CDH7.1.1启用Kerberos
- 持续代码质量管理-SonarQube Scanner部署 2.1. 软件安装2.2. 配置修改
- 《前端那些事》聊聊前端的按需加载