1 . 先创建一个工具类 EasyExcelUtils
package com.pla.common.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.pla.common.exception.PlaException;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* EasyExcel工具类
*/
public class EasyExcelUtils {
/**
* 通过路径,读取excel所有数据
* @param fileName excel文件路径
* @param aClass 映射对象class
* @return 与excel对应的list集合
*/
public static<T> List<T> getListByPathName(String fileName,Class<?> aClass){
if (fileName.isEmpty()) {
return null;
}
List<T> list = new ArrayList<>();
AnalysisEventListener<T> analysisEventListener = new AnalysisEventListener<T>(){
@Override
public void invoke(T obj, AnalysisContext analysisContext) {
list.add(obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
};
EasyExcel.read(fileName,aClass,analysisEventListener).sheet().doRead();
return list;
}
/**
* 通过流,读取excel所有数据,返回对应的对象list集合
* @param file excel文件流
* @param aClass 映射对象class
* @return 与excel对应的list集合
*/
public static<T> List<T> getListByFile(MultipartFile file, Class<?> aClass) {
List<T> list = new ArrayList<>();
AnalysisEventListener<T> analysisEventListener = new AnalysisEventListener<T>(){
@Override
public void invoke(T obj, AnalysisContext analysisContext) {
list.add(obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
};
try {
EasyExcel.read(file.getInputStream(),aClass,analysisEventListener).sheet().doRead();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 通过对象list集合得到outPutStream
* @param List 对象集合
* @return excel文件流
*/
public static <T> boolean setByListToPathName(String pathName, List<T> List) {
if (pathName.isEmpty() || List.isEmpty()) {
return false;
}
EasyExcel.write(pathName,List.get(0).getClass()).sheet().doWrite(List);
return true;
}
/**
* 通过对象list写入outputStream
* @param List 对象集合
* @return excel文件流
*/
public static <T> boolean setByListToOutputStream(OutputStream outputStream, List<T> List) {
if (List.isEmpty()) {
return false;
}
EasyExcel.write(outputStream,List.get(0).getClass()).sheet().doWrite(List);
return true;
}
/**
* 通过EasyExcel的list对象,对response的OutputStream进行填充返回给浏览器
* @param response HttpServletResponse对象
* @param fileName 文件名
* @param easyExcelList EasyExcel的list对象
* @param <T> 泛型
* @throws IOException
*/
public static <T> void resposeEasyExcel(HttpServletResponse response,String fileName,List<T> easyExcelList) throws IOException{
if (fileName.isEmpty()) {
throw new PlaException("文件名不能为空",400);
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String newfileName = null;
newfileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + newfileName + ".xlsx");
setByListToOutputStream(response.getOutputStream(),easyExcelList);
}
}
2.创建实体类(和想导入的excel表的属性相等)
package com.pla.model.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
public class EngineeringProjectExcel implements Serializable {
//value:表头名称 index :内容的顺序
@ExcelProperty(value ="工程项目名称" , index = 0)
@ColumnWidth(20) //设置宽度
private String projectName;
@ExcelProperty(value = "工程项目编码" , index = 1)
@ColumnWidth(20) //设置宽度
private String projectCode;
}
3.Controller层(导入)
@RestController
@RequestMapping("/projectInfoManage")
@CrossOrigin(origins = "*",allowCredentials = "true") //解决跨域问题
public class EngineeringProjectInfoController {
@Autowired
private EngineeringProjectInfoService engineeringProjectInfoService;
/**
* Eccel表格导入
* @param file
* @return
*/
@ApiOperation("Excel表格导入")
@PostMapping("/excelImport")
public Result excelImport(MultipartFile file){
List<EngineeringProjectInfo> list = new ArrayList<>();
//调用工具类的方法
List<EngineeringProjectExcel> listByFile = EasyExcelUtils.getListByFile(file,
EngineeringProjectExcel.class);
//遍历excel表格中的数据
for (EngineeringProjectExcel projectExcel : listByFile) {
EngineeringProjectInfo engineeringProjectInfo = new EngineeringProjectInfo();
BeanUtils.copyProperties(projectExcel , engineeringProjectInfo);
list.add(engineeringProjectInfo);
}
boolean b = engineeringProjectInfoService.saveBatch(list);
if (b){
return Result.ok(b);
}
return Result.fail();
}
}
4.Controller(导出到浏览器 注意:不要用Swagger进行访问会导致很多问题 ,可以直接用浏览器也可以用postman)
@RestController
@RequestMapping("/projectInfoManage")
@CrossOrigin(origins = "*",allowCredentials = "true") //解决跨域问题
public class EngineeringProjectInfoController {
@Autowired
private EngineeringProjectInfoService engineeringProjectInfoService;
/**
* Excel表格导出
* @param fileName
* @param response
* @return
*/
@ApiOperation("Excel表格导出")
@GetMapping("/engineeringprojectInfoExcelExport")
public Result engineeringprojectInfoExcelExport(HttpServletResponse response,String
fileName) throws IOException{
List<EngineeringProjectExcel> engineeringProjectExcel = new ArrayList<>();
//查询数据
List<EngineeringProjectInfo> list = engineeringProjectInfoService.list();
//遍历查询出的数据
for (EngineeringProjectInfo projectInfo : list) {
EngineeringProjectExcel excel = new EngineeringProjectExcel();
BeanUtils.copyProperties(projectInfo , excel);
engineeringProjectExcel.add(excel);
}
//调工具类中的方法
EasyExcelUtils.resposeEasyExcel(response,fileName,engineeringProjectExcel);
return Result.ok();
}