Spring Boot 集成 easypoi实现excel的多sheet导入导出
2023-09-11 14:20:19 时间
Spring Boot 集成 easypoi实现excel的多sheet导入导出
一、excel多sheet导入
1.导入依赖
<!--easypoi依赖,实现excel文件导入导出-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
2.定义两个导入导出实体类
package com.example.exceldemo.excel;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
/**
* 用户
* @author qzz
*/
@Data
public class UserExcel implements Serializable {
/**
* 姓名
*/
@Excel(name = "姓名")
private String name;
/**
* 年龄
*/
@Excel(name = "年龄",type = 10)
private Integer age;
/**
* 性别
*/
@Excel(name = "性别")
private String sexStr;
/**
* 手机号
*/
@Excel(name = "手机号")
private String phone;
/**
* 备注
*/
@Excel(name = "备注")
private String remarks;
/**
* 性别 0 男 1 女
*/
private Integer sex;
}
package com.example.exceldemo.excel;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 商品
* @author qzz
*/
@Data
public class ProductExcel implements Serializable {
/**
* 标题
*/
@Excel(name = "标题")
private String title;
/**
* 副标题
*/
@Excel(name = "副标题")
private String subTitle;
/**
* 售价
* type:导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本
*/
@Excel(name = "售价",type = 10,numFormat = "#.##")
private BigDecimal salePrice;
}
3.Controller添加excel导入方法
package com.example.exceldemo.controller;
import cn.hutool.core.bean.BeanUtil;
import com.example.exceldemo.common.Result;
import com.example.exceldemo.entity.Product;
import com.example.exceldemo.entity.User;
import com.example.exceldemo.excel.ProductExcel;
import com.example.exceldemo.excel.UserExcel;
import com.example.exceldemo.service.ProductService;
import com.example.exceldemo.service.UserService;
import com.example.exceldemo.utils.ExcelUtils;
import com.example.exceldemo.utils.ListUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 教师
* @author qzz
*/
@RestController
@RequestMapping("/teacher")
public class TestController {
@Autowired
private UserService userService;
@Autowired
private ProductService productService;
/**
* 批量导入 多sheet
* @param multipartFile
* @return
*/
@RequestMapping("/upload")
public Result importExcel(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
try{
//标题占几行
Integer titleRows =1;
//表头占几行
Integer headerRows =1;
String originalFileName = multipartFile.getOriginalFilename();
String suffix = Objects.requireNonNull(originalFileName).substring(originalFileName.lastIndexOf(".") + 1);
File file = File.createTempFile(suffix, String.valueOf(System.currentTimeMillis()));
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
Workbook workBook = ExcelUtils.getWorkBook(file);
for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
String sheetName = workBook.getSheetAt(numSheet).getSheetName();
System.out.println("sheet名:"+sheetName);
if(numSheet==0){
//用户信息列表导入
List<User> userList = new ArrayList<>();
List<UserExcel> userExcelList = ExcelUtils.importExcelMore(file, titleRows, headerRows, numSheet, UserExcel.class);
for(UserExcel userExcel:userExcelList){
User user = new User();
BeanUtil.copyProperties(userExcel,user);
user.setSex(userExcel.getSexStr().equals("男")?0:1);
user.setStatus(0);
userList.add(user);
}
//批量新增用户
userService.addBatchUser(userList);
}else if(numSheet==1){
//商品信息列表导入
List<ProductExcel> productExcelList = ExcelUtils.importExcelMore(file, titleRows, headerRows, numSheet, ProductExcel.class);
List<Product> productList = new ListUtils<Product>().copyProperties(productExcelList, Product.class);
//批量新增用户
productService.addBatchProduct(productList);
}
}
return Result.success("上传成功:"+originalFileName);
}catch (Exception e){
e.printStackTrace();
return Result.fail("上传失败");
}
}
}
二、excel多sheet导出
导出方法:
/**
* 导出excel 多sheet
* @param response
*/
@RequestMapping("/exportExcelSheets")
public void exportExcel(HttpServletResponse response) {
//excel多sheet导出
Workbook workbook = null;
try {
//创建参数对象(用来设定excel的sheet1内容等信息)
ExportParams userExportParams = new ExportParams();
//设置sheet的名称
userExportParams.setSheetName("用户表信息");
//设置sheet表头名称
userExportParams.setTitle("用户列表");
//创建sheet1使用map
Map<String, Object> userExportMap = new HashMap<>();
//title的参数为ExportParams类型,目前仅仅在ExportParams中设置了sheetName
userExportMap.put("title", userExportParams);
//模板导出对应的实体类型
userExportMap.put("entity", UserExcel.class);
//获取要导出的用户列表
List<UserExcel> users = userService.findUserList();
//sheet1中要填充的数据
userExportMap.put("data", users);
//创建参数对象(用来设定excel的sheet2内容等信息)
ExportParams productExportParams = new ExportParams();
//设置sheet的名称
productExportParams.setSheetName("商品表信息");
//设置sheet表头名称
productExportParams.setTitle("商品列表");
//创建sheet2使用map
Map<String, Object> productExportMap = new HashMap<>();
//title的参数为ExportParams类型,目前仅仅在ExportParams中设置了sheetName
productExportMap.put("title", productExportParams);
//模板导出对应的实体类型
productExportMap.put("entity", ProductExcel.class);
//获取要导出的用户列表
List<ProductExcel> productExcelList = productService.findProductList();
//sheet1中要填充的数据
productExportMap.put("data", productExcelList);
//将sheet1、sheet2使用Map进行包装
List<Map<String, Object>> sheetsList = new ArrayList<>();
//后续增加sheet组,则后面继续追加即可;
sheetsList.add(userExportMap);
sheetsList.add(productExportMap);
//执行方法
workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
//设置编码格式
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
//设置内容类型
response.setContentType("application/octet-stream");
//设置头及文件命名
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户、商品信息导出", StandardCharsets.UTF_8.name()));
//写出流
workbook.write(response.getOutputStream());
}catch (Exception e){
e.printStackTrace();
}finally {
if(workbook != null){
try {
//强行关流
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
相关文章
- html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式
- Spring注解?啥玩意?
- Spring Bean的生命周期(非常详细)
- Spring Boot 2.5.0 重新设计的spring.sql.init 配置有啥用?
- Spring集成Redis集群(含spring集成redis代码)
- SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域
- Spring整合CXF步骤,Spring实现webService,spring整合WebService
- Python Excel教程之如何将多个 excel 文件合并为一个文件(教程含源码)
- Spring Security 实战干货:基于注解的接口角色访问控制
- Python Excel自动化之 如何根据某一列快速对比两excel文件不同并输出不同内容
- Excel 函数教程之VLOOKUP实用教程与10个适用于初学者和高级用户的VLOOKUP案例(教程含数据excel)
- Excel VLOOKUP实用教程之 05 vlookup如何从列表中获取最后一个值?(教程含数据excel)
- 通过spring,在项目的任意位置获取当前Request
- spring框架漏洞整理(Spring Cloud Config路径穿越导致的信息泄露)
- spring框架漏洞整理(Spring Boot Actuator命令执行漏洞)
- spring框架漏洞整理(Spring Boot Actuator相关漏洞)
- EXCEL excel中运用ctrl+D、ctrl+enter、ctrl+E批量填充数据
- spring mvc Spring Data Redis RedisTemplate [转]
- Spring Boot 集成 easypoi实现excel的导入导出、excel导入导出含图片
- 【spring框架】引用外部资源文件
- spring cloud
- Spring MVC handler interceptors example--转载
- 曹工谈Spring Boot:Spring boot中怎么进行外部化配置,一不留神摔一跤;一路debug,原来是我太年轻了
- 曹工说Spring Boot源码(7)-- Spring解析xml文件,到底从中得到了什么(上)