当前位置:   article > 正文

springboot整合Excel导入导出_springboot 生成数据导出脚本

springboot 生成数据导出脚本

目录

引入依赖

读Excel

excel文件 

编写导出数据的实体

输出 

读取Excel文件

写Excel

编写导出数据的实体

准备数据并写入到文件

导出Excel文件

文件上传

导入依赖

 controller

 监听器

实现类StudentServiceImpl

文件下载

controller


引入依赖

  1. <!-- EasyExcel -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.2.6</version>
  6. </dependency>
  7. <!-- lombok 优雅编程 -->
  8. <dependency>
  9. <groupId>org.projectlombok</groupId>
  10. <artifactId>lombok</artifactId>
  11. <version>1.18.10</version>
  12. </dependency>
  13. <!-- junit -->
  14. <dependency>
  15. <groupId>junit</groupId>
  16. <artifactId>junit</artifactId>
  17. <version>4.12</version>
  18. </dependency>

读Excel

excel文件 

编写导出数据的实体

  1. import com.alibaba.excel.annotation.ExcelProperty;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.util.Date;
  6. @Data
  7. @NoArgsConstructor
  8. @AllArgsConstructor
  9. public class Student {
  10. /**
  11. * 学生姓名
  12. */
  13. @ExcelProperty("学生姓名")
  14. private String name;
  15. /**
  16. * 学生性别
  17. */
  18. @ExcelProperty("学生性别")
  19. private String gender;
  20. /**
  21. * 学生出生日期
  22. */
  23. @ExcelProperty("学生出生日期")
  24. private Date birthday;
  25. /**
  26. * id
  27. */
  28. private String id;
  29. }

输出 

读取Excel文件

调用EasyExcelAPI读取的Excel文件的测试类StudentReadDemo

  1. import com.alibaba.excel.EasyExcel;
  2. import com.alibaba.excel.read.builder.ExcelReaderBuilder;
  3. import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
  4. import com.example.demo.component.StudentReadListener;
  5. import com.example.demo.model.Student;
  6. import java.io.FileNotFoundException;
  7. public class StudentReadDemo {
  8. public static void main(String[] args) throws FileNotFoundException {
  9. // 读取文件,读取完之后会自动关闭
  10. /*
  11. head 每行数据对应的实体;Student.class
  12. readListener 读监听器,每读一样就会调用一次该监听器的invoke方法
  13. sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字,不传默认为0
  14. */
  15. // 封装工作簿对象
  16. ExcelReaderBuilder workBook = EasyExcel.read("src/main/resources/excel/student.xlsx", Student.class, new StudentReadListener());
  17. // 封装工作表
  18. ExcelReaderSheetBuilder sheet1 = workBook.sheet();
  19. // 读取
  20. sheet1.doRead();
  21. }
  22. }

 读取Excel的监听器,用于处理读取产生的数据

  1. import com.alibaba.excel.context.AnalysisContext;
  2. import com.alibaba.excel.event.AnalysisEventListener;
  3. import com.example.demo.model.Student;
  4. /**
  5. * @Author Vsunks.v
  6. * @Date 2020/3/11 23:12
  7. * @Description:
  8. */
  9. public class StudentReadListener extends AnalysisEventListener<Student> {
  10. // 每读一样,会调用该invoke方法一次
  11. @Override
  12. public void invoke(Student data, AnalysisContext context) {
  13. System.out.println("data = " + data);
  14. }
  15. // 全部读完之后,会调用该方法
  16. @Override
  17. public void doAfterAllAnalysed(AnalysisContext context) {
  18. // TODO......
  19. }
  20. }

写Excel

编写导出数据的实体

  1. import com.alibaba.excel.annotation.ExcelIgnore;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import com.alibaba.excel.annotation.write.style.ColumnWidth;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import java.util.Date;
  8. @Data
  9. @AllArgsConstructor
  10. @NoArgsConstructor
  11. @ColumnWidth(20)
  12. public class Student {
  13. /**
  14. * id
  15. */
  16. //@ExcelProperty(value = "编号",index = 3)
  17. @ExcelIgnore
  18. private String id;
  19. /**
  20. * 学生姓名
  21. */
  22. @ExcelProperty(value = "学生姓名", index = 0)
  23. //@ColumnWidth(30)
  24. private String name;
  25. /**
  26. * 学生性别
  27. */
  28. @ExcelProperty(value = "学生性别", index = 2)
  29. private String gender;
  30. /**
  31. * 学生出生日期
  32. */
  33. @ExcelProperty(value = "学生出生日期", index = 1)
  34. //@ColumnWidth(20)
  35. private Date birthday;
  36. }

准备数据并写入到文件

  1. import com.alibaba.excel.EasyExcel;
  2. import com.alibaba.excel.write.builder.ExcelWriterBuilder;
  3. import com.example.demo.model.Student;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.List;
  7. /**
  8. * @Author Vsunks.v
  9. * @Date 2020/3/11 23:27
  10. * @Description:
  11. */
  12. public class StudentWriteDemo {
  13. public static void main(String[] args) {
  14. List<Student> students = initData();
  15. /*
  16. String pathName 写入文件的路径
  17. Class head 写入文件的对象类型
  18. 默认写入到07的xlsx中,如果想要写入xls,可以指定类型(待验证)
  19. */
  20. ExcelWriterBuilder workBook = EasyExcel.write("src/main/resources/excel/student-temp.xlsx", Student.class);
  21. // sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字
  22. workBook.sheet().doWrite(students);
  23. }
  24. private static List<Student> initData() {
  25. ArrayList<Student> students = new ArrayList<>();
  26. for (int i = 0; i < 10; i++) {
  27. Student data = new Student();
  28. data.setName("学生" + i);
  29. data.setBirthday(new Date());
  30. if (i%2==0){
  31. data.setGender("女");
  32. }
  33. data.setGender("男");
  34. students.add(data);
  35. }
  36. return students;
  37. }
  38. }

导出Excel文件

文件上传

导入依赖

  1. <!-- SpringMVC(Spring) -->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-webmvc</artifactId>
  5. <version>5.0.5.RELEASE</version>
  6. </dependency>
  7. <!-- Servlet -->
  8. <dependency>
  9. <groupId>javax.servlet</groupId>
  10. <artifactId>javax.servlet-api</artifactId>
  11. <version>4.0.1</version>
  12. <scope>provided</scope>
  13. </dependency>
  14. <!-- 文件上传 -->
  15. <dependency>
  16. <groupId>commons-fileupload</groupId>
  17. <artifactId>commons-fileupload</artifactId>
  18. <version>1.4</version>
  19. </dependency>

 controller

  1. import com.alibaba.excel.EasyExcel;
  2. import com.alibaba.excel.read.builder.ExcelReaderBuilder;
  3. import com.example.demo.component.StudentReadListener;
  4. import com.example.demo.model.Student;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. @Controller
  11. public class WebUploadAndDownload {
  12. /**
  13. * 文件上传
  14. * 1. 编写excel中每一行对应的实体类
  15. * 2. 由于默认异步读取excel,所以需要逐行读取的回调监听器
  16. * 3. 开始读取Excel
  17. */
  18. @PostMapping("upload")
  19. @ResponseBody
  20. public String upload(MultipartFile file) throws IOException {
  21. ExcelReaderBuilder workBook = EasyExcel.read(file.getInputStream(), Student.class,new StudentReadListener());
  22. workBook.sheet().doRead();
  23. return "success";
  24. }
  25. }

 监听器

  1. @Component
  2. @Scope("prototype") // 作者要求每次读取都要使用新的Listener
  3. public class StudentReadListener extends AnalysisEventListener<Student> {
  4. @Autowired
  5. private StudentService studentService;
  6. private final int BATCH_SAVE_NUM = 5;
  7. ArrayList<Student> students = new ArrayList<>();
  8. private int count = 0;
  9. // 每读一样,会调用该invoke方法一次
  10. @Override
  11. public void invoke(Student data, AnalysisContext context) {
  12. students.add(data);
  13. if (++count % BATCH_SAVE_NUM == 0) {
  14. studentService.save(students);
  15. students.clear();
  16. }
  17. }
  18. // 全部读完之后,会调用该方法
  19. @Override
  20. public void doAfterAllAnalysed(AnalysisContext context) {
  21. // TODO......
  22. }
  23. }

实现类StudentServiceImpl

  1. public interface StudentService {
  2. void save(ArrayList<Student> students);
  3. }
  4. @Service
  5. public class StudentServiceImpl implements StudentService {
  6. @Override
  7. public void save(ArrayList<Student> students) {
  8. System.out.println("students in service = " + students);
  9. }
  10. }

文件下载

controller

  1. public class WebUploadAndDownload {
  2. /**
  3. * 文件下载
  4. * 1. 编写实体类并创建对象以便写入表格
  5. * 2. 设置响应参数:文件的ContentType和文件名,同时设置编码避免乱码
  6. * 3. 直接写,内部会调用finish方法自动关闭OutputStream
  7. */
  8. @GetMapping("download")
  9. public void download(HttpServletResponse response) throws IOException {
  10. response.setContentType("application/vnd.ms-excel");
  11. response.setCharacterEncoding("utf-8");
  12. // 防止中文乱码
  13. String fileName = URLEncoder.encode("测试", "UTF-8");
  14. response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
  15. ExcelWriterBuilder workBook = EasyExcel.write(response.getOutputStream(), Student.class);
  16. ExcelWriterSheetBuilder sheet = workBook.sheet("模板");
  17. sheet.doWrite(initData());
  18. }
  19. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/551637
推荐阅读
相关标签
  

闽ICP备14008679号