"Java tool class" EasyExcelUtil tool class excel import and export tool class Ali EasyExcel is simple and powerful, and no poi is required

Keywords: Java easyexcel

Introduction

This number is mainly the sharing of common key technology points and common tool classes of Java; And technology sharing of integration frameworks such as springboot+springcloud+Mybatisplus+druid+mysql+redis+swagger+maven+docker; Technology sharing of big data processing frameworks such as datax, kafka and flink. The article will be updated constantly. Code friends are welcome to pay attention, like collection and forwarding!

I hope all code friends can click to pay attention and make 1000 powder. Some video tutorials will be recorded later, combining graphics and video, such as Book Introduction website system, rush purchase system, big data middle desk system, etc. Technology is the favorite of program apes. Code friends rush

If the coder thinks the code is too long, he can quickly scan it from beginning to end and understand it. If you find it useful, you can forward it for collection in case of need.

Text:

The excel import and export tool class was sorted out today. I saw that the version 1.x used in the next project was actually upgraded to the latest version of easyexcel 3.0.2. Unexpectedly, a pile of code encapsulated before was not needed. Now this version is very easy to use. You can directly use the method of easyexcel. One more layer of encapsulation is just for the convenience of the project.

Example 1

Read test

@Test
 public void readTest(){
     // Read test
     String readFile = "D:\\Workspace\\IdeaProjects\\jtool-common\\student Information sheet 2.xlsx";
     List<Student> data = EasyExcelUtil.read(readFile, Student.class);
     printList(data);
 }
 private static void printList(List<?> datas) {
     int i = 0;
     for (Object ob : datas) {
         System.out.println(i++ + "=>" + ob);
     }
 }
 ​
 // Console printing
 17:55:58.240 [main] INFO  - Parsing complete! Read 10 lines
 0=>Student(name=Zhang 1, age=12, address=Building 0 in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 1=>Student(name=Zhang 1, age=13, address=1 building in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 2=>Student(name=Zhang 1, age=14, address=2 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 3=>Student(name=Zhang 1, age=15, address=3 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 4=>Student(name=Zhang 1, age=16, address=4 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 5=>Student(name=Zhang 1, age=17, address=5 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 6=>Student(name=Zhang 1, age=18, address=6 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 7=>Student(name=Zhang 1, age=19, address=7 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 8=>Student(name=Zhang 1, age=20, address=8 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)
 9=>Student(name=Zhang 1, age=21, address=9 buildings in Shenzhen, birthday=Wed Nov 03 12:17:46 GMT+08:00 2021)

Example 2

Write test

@Test
 public void writeTest(){
     // Write test
     List<Student> stus = new ArrayList<>();
     for (int i = 0; i < 10; i++) {
         stus.add(new Student("Zhang 1", 12 + i, "Shenzhen" + i + "Building", new Date()));
     }
     String file = "student Information sheet 2.xlsx";
     EasyExcelUtil.write(file, stus);
 }
 ​
 // There is no output on the console. You can find the exported file student information table 2.xlsx in the project and directory

Example 3

Directly return to the browser for download

@RequestMapping(value = "/download", method = RequestMethod.GET)
 public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
 ​
     // Write test
     List<Student> stus = new ArrayList<>();
     for (int i = 0; i < 10; i++) {
         stus.add(new Student("Zhang 1", 12 + i, "Shenzhen" + i + "Building", new Date()));
     }
     EasyExcelUtil.download(response, stus, "Student information sheet");
     return "";
 }

The contents of the files exported in examples 2 and 3 are as follows:

 

Tool source code:

import com.alibaba.excel.EasyExcel;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 ​
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.net.URLEncoder;
 import java.util.List;
 ​
 /**
  * excel Tool class
  * easyexcel The 3.0.2 version used is very different from the previous version, and is incompatible with the 1.x version
  *
  * @author liangxn
  */
 public class EasyExcelUtil {
 ​
     private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelUtil.class);
 ​
     public static <T> List<T> read(String filePath, final Class<?> clazz) {
         File f = new File(filePath);
         try (FileInputStream fis = new FileInputStream(f)) {
             return read(fis, clazz);
         } catch (FileNotFoundException e) {
             LOGGER.error("file{}non-existent", filePath, e);
         } catch (IOException e) {
             LOGGER.error("File read error", e);
         }
 ​
         return null;
     }
 ​
     public static <T> List<T> read(InputStream inputStream, final Class<?> clazz) {
         if (inputStream == null) {
             throw new MyAppRunException("Parsing error, file stream is null");
         }
 ​
         // A very important point is that the DataListener cannot be managed by spring. It needs to read new every time excel is read, and then spring can be used to construct methods to pass in
         DataListener<T> listener = new DataListener<>();
 ​
         // Here, you need to specify which class to read, and then read the first sheet file. The stream will close automatically
         EasyExcel.read(inputStream, clazz, listener).sheet().doRead();
         return listener.getRows();
     }
 ​
     public static void write(String outFile, List<?> list) {
         Class<?> clazz = list.get(0).getClass();
         // The new version will automatically close the stream and does not need to operate by itself
         EasyExcel.write(outFile, clazz).sheet().doWrite(list);
     }
 ​
     public static void write(String outFile, List<?> list, String sheetName) {
         Class<?> clazz = list.get(0).getClass();
         // The new version will automatically close the stream and does not need to operate by itself
         EasyExcel.write(outFile, clazz).sheet(sheetName).doWrite(list);
     }
 ​
     public static void write(OutputStream outputStream, List<?> list, String sheetName) {
         Class<?> clazz = list.get(0).getClass();
         // The new version will automatically close the stream and does not need to operate by itself
         // sheetName is the name of the sheet. The first sheet is written by default
         EasyExcel.write(outputStream, clazz).sheet(sheetName).doWrite(list);
     }
 ​
     /**
      * File download (if it fails, an excel with partial data will be returned), which is used to directly return Excel to the browser for download
      */
     public static void download(HttpServletResponse response, List<?> list, String sheetName) throws IOException {
         Class<?> clazz = list.get(0).getClass();
 ​
         // Note that some students have reported that using swagger will lead to various problems. Please use the browser or postman directly
         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
         response.setCharacterEncoding("utf-8");
         // Here, URLEncoder.encode can prevent Chinese random codes. Of course, it has nothing to do with easyexcel
         String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
         response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
         EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(list);
     }
 ​
 }

Other related classes

import com.alibaba.excel.annotation.ExcelProperty;
 import com.alibaba.excel.annotation.format.DateTimeFormat;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 ​
 import java.util.Date;
 ​
 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 public class Student {
     @ExcelProperty(value = "full name", index = 0)
     private String name;
 ​
     @ExcelProperty(value = "Age", index = 1)
     private int age;
 ​
     @ExcelProperty(value = "address", index = 2)
     private String address;
 ​
     // easyexcel Date type does not support LocalDate, it can only be Date
     @ExcelProperty(value = "birthday", index = 3)
     @DateTimeFormat("yyyy-MM-dd")
     private Date birthday;
 }


 /**
  * General exception class
  */
 public class MyAppRunException extends RuntimeException {
 ​
     public MyAppRunException(String message) {
         super(message);
     }
 ​
     public MyAppRunException(String message, Throwable cause) {
         super(message, cause);
     }
 ​
     public MyAppRunException(Throwable cause) {
         super(cause);
     }
 ​
     protected MyAppRunException(String message,
             Throwable cause,
             boolean enableSuppression,
             boolean writableStackTrace) {
         super(message, cause, enableSuppression, writableStackTrace);
     }
 ​
 }

I have been coding for more than ten years and have accumulated some tool classes in the project. Many tool classes are used in every project and are very practical. Most of them are encapsulated by me. Some tool classes are encapsulated by colleagues. Some tool classes don't remember whether they are ctrl+c or encapsulated by themselves. Now I will summarize most of the tool classes in the project and share them with you when I am free. If the code involved in the article has infringement, please notify me for handling.

The plan is to sort out the tools first. As the saying goes, if you want to do well, you must first sharpen the tools. In the project, whether it is an ordinary single project, a multi module maven project or a distributed microservice, some functional modules can be reused, and the tool module is one of them.

Posted by daarius on Wed, 03 Nov 2021 18:30:24 -0700