1、开发工具:idea2018.1
2、jar 管理:maven 3.3.3
3、项目类型:springboot
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.5.6
com.ygq
apps
0.0.1-SNAPSHOT
apps
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-data-jdbc
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
com.alibaba
druid
1.1.21
com.baomidou
mybatis-plus-core
3.4.1
com.alibaba
easyexcel
2.2.6
com.github.whvcse
easy-captcha
1.6.2
org.apache.commons
commons-lang3
3.6
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.ygq.apps.domain.Student;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* excel工具类
*
*/
public class ExcelUtils {
/**
* Excel导出
*
* @param response response
* @param fileName 文件名
* @param sheetName sheetName
* @param list 数据List
* @param pojoClass 对象Class
*/
public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List> list,
Class> pojoClass) throws IOException {
if(StringUtils.isBlank(fileName)){
//当前日期
fileName = DateUtils.format(new Date());
}
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), pojoClass).sheet(sheetName).doWrite(list);
}
/**
* Excel导出,先sourceList转换成List,再导出
*
* @param response response
* @param fileName 文件名
* @param sheetName sheetName
* @param sourceList 原数据List
* @param targetClass 目标对象Class
*/
public static void exportExcelToTarget(HttpServletResponse response, String fileName, String sheetName, List> sourceList,
Class> targetClass) throws Exception {
List
@RestController
@RequestMapping("excel")
public class EasyExcelController {
@Autowired
StudentService studentService;
/**
* 导入
* @param file
*/
@PostMapping("import")
public void importExcel(@RequestParam("file") MultipartFile file) {
try {
List list = ExcelUtils.importExcelToTarget(file, Student.class);
for (Object student : list) {
Student stu= (Student) student;
System.out.println(stu);
}
} catch (Exception e) {
System.out.println("导入失败" + e);
}
}
/**
* 导出
* @param response
*/
@GetMapping("export")
public void exporttExcel(HttpServletResponse response) {
try {
List list = studentService.list();
ExcelUtils.exportExcel(response,null,null,list,Student.class);
} catch (Exception e) {
System.out.println("导出失败" + e);
}
}
@GetMapping("list")
public List list() {
List list = studentService.list();
System.out.println(list);
return list;
}
}
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@ExcelProperty("用户id",index=0)
private Long id;
@ExcelProperty("姓名",index=1)
private String name;
@ExcelProperty("年龄",index=2)
private Integer age;
@ExcelProperty("性别",index = 3,converter = SexConverter.class)
private Integer sex;
@ExcelProperty("地址",index=4)//导出Excel表格的字段名称
private String address;
@ExcelIgnore//导出时忽略某个字段
private Long product_id;
}
字段转换(在封装实体时,自动转换)
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class SexConverter implements Converter {
@Override
public Class supportJavaTypeKey() {
return null;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return null;
}
@Override
public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if(integer == 1){
return new CellData("男");
}else {
return new CellData("女");
}
}
}
public class Test{
@Data
@ColumnWidth(20)
public static class TestVO {
@ExcelProperty( value = "姓名",index = 0)
private String name;
@ExcelProperty( value = "年龄",index = 1)
private int age;
@ExcelProperty( value = "学校",index = 2)
private String school;
}
/**
* 多个sheet导入测试
* @throws FileNotFoundException
*/
@Test
public void sheetImport() throws FileNotFoundException {
// 输出流
OutputStream outputStream = null;
outputStream = new FileOutputStream(new File("D:/1.xlsx"));
// 导出的数据
List dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
TestVO testVO = new TestVO();
testVO.setAge(i + 20);
testVO.setName("vo" + i);
testVO.setSchool("school" + i);
dataList.add(testVO);
}
// 标题
List headList = Arrays.asList("姓名", "年龄", "学校");
// 测试多sheel导出
ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
WriteSheet test1 = EasyExcel.writerSheet(0, "test1").head(TestVO.class).build();
WriteSheet test2 = EasyExcel.writerSheet(1, "test2").head(TestVO.class).build();
excelWriter.write(dataList,test1).write(dataList,test2);
excelWriter.finish();
}
}
如果导出需加样式, 示例
// 表头样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 单元格样式
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 初始化表格样式
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
WriteSheet test1 = EasyExcel.writerSheet(0, "test1").head(TestVO.class).
registerWriteHandler(horizontalCellStyleStrategy).build();
public class Test{
@Data
@ColumnWidth(20)
public static class TestVO {
@ExcelProperty( value = "姓名",index = 0)
private String name;
@ExcelProperty( value = "年龄",index = 1)
private int age;
@ExcelProperty( value = "学校",index = 2)
private String school;
}
@Data
@ColumnWidth(20)
public static class TestVO1 {
@ExcelProperty( value = "姓名",index = 0)
private String name;
@ExcelProperty( value = "年龄",index = 1)
private int age;
@ExcelProperty( value = "学校",index = 2)
private String school;
}
/**
* 测试导入多个sheet导入
* @throws Exception
*/
@Test
public void read() throws Exception {
String filePath = "D:/1.xlsx";
InputStream inputStream = null;
inputStream = new FileInputStream(new File(filePath));
AnalysisEventListenerImpl listener = new AnalysisEventListenerImpl<>();
ExcelReader excelReader = EasyExcel.read(inputStream,listener).build();
// 第一个sheet读取类型
ReadSheet readSheet1 = EasyExcel.readSheet(0).head(TestVO.class).build();
// 第二个sheet读取类型
ReadSheet readSheet2 = EasyExcel.readSheet(1).head(TestVO1.class).build();
// 开始读取第一个sheet
excelReader.read(readSheet1);
List list = listener.getDatas();
list.forEach((user)->{
TestVO user1= (TestVO) user;
System.out.println(user1.getName()+", "+user1.getAge()+", "+user1.getSchool());
});
// 清空之前的数据
listener.getDatas().clear();
// 开始读取第二个sheet
excelReader.read(readSheet2);
System.out.println("---------------------------------");
List list2 = listener.getDatas();
list2.forEach((user)->{
TestVO1 user2= (TestVO1) user;
System.out.println(user2.getName()+", "+user2.getAge()+", "+user2.getSchool());
});
}
}