赞
踩
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
@ToString @Data //set、get、toString方法 @NoArgsConstructor //无参构造方法 @ExcelIgnoreUnannotated //没有标注的字段不被导出文件 public class Student{ @ExcelProperty("编号") private Integer id; @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private Integer age; @ExcelProperty("电话") private String phone; @ExcelProperty("生日") private Date birthday; public Student(String name,Integer age,Integer id){ this.name = name; this.age = age; this.id = id; } }
public class StudentReadListener implements ReadListener<Student>{ List<Student> list = new ArrayList<>(); //每读一行触发一次 @Override public void invoke(Student student,AnalysisContext analysisContext){ System.out.println("读取到"+student); list.add(student); } //都读完后触发一次 @Override public void doAfterAllAnalysed(AnalysisContext analysisContext){ System.out.println("读取完毕"); } }
public void importExcel() throws FileNotFoundException{ //1. 读取文件的流 File file = new File("D:/student.xlsx"); InputStream is = new FileInputStream(file); //2. 创建一个读取监听器 StudentReadListener listener = new StudentReadListener(); //3. 导入的参数配置 EasyExcel.read(is,Student.class,listener) .excelType(ExcelTypeEnum.CSV) .sheet(0) //读第几个工作表,从0开始 .headRowNumber(1) //列头占几行 .doRead(); ) }
//这是导出Excel表格的参数配置
EasyExcel.write(response.getOutputStream())
.head(Student.class)
.excelType(ExcelTypeEnum.XLSX)
.sheet("数据")
.doWrite(list);
}
//同样应用于导入Excel表格的参数配置
EasyExcel.read(inputStream, Student.class,listener)
.excelType(ExcelTypeEnum.XLSX)
.sheet("数据") //读第几个工作表,从0开始
.headRowNumber(1) //列头占几行
.doRead();
@GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { List<Student> list = new ArrayList<>(); list.add(new Student("梅超风",19,3342)); list.add(new Student("西门灵风",39,5621)); list.add(new Student("司马长风",25,82145)); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); response.setCharacterEncoding("utf-8"); //设定要导出的excel的文件名 String fileName = URLEncoder.encode("student","UTF-8").replaceAll("\\+","%20"); response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx"); //导出Excel表格 EasyExcel.write(response.getOutputStream()) .head(Student.class) .excelType(ExcelTypeEnum.XLSX) .sheet("数据") .doWrite(list); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。