Steps for SpringBoot to integrate EasyExcel

  • 2021-09-20 20:21:40
  • OfStack

Directory 1, Introduction to EasyExcel 2. Commonly used notes
3. Dependence 4. Listening 5. Interface Import Excel6. Interface Export Excel (HttpServletResponse response, HttpServletRequest request) 7. Local Import, Local Export

1. Introduction to EasyExcel

EasyExcel Advantage

Annotated custom action. The input and output are simple, and the interface of input and output process is provided Support flexible operations such as cell merging to a certain extent

2. Commonly used notes

@ ExcelProperty specifies that the current field corresponds to the 1 column in excel. You can match by name or Index. Of course, you can not write it. By default, the first field is index=0, and so on. Be careful, either don't write it all, use index all, or match it all with names. Don't mix three, unless you know very well how to sort three in the source code. @ ExcelIgnore by default all fields will match excel. If you add this annotation, this field will be ignored @ DateTimeFormat date conversion, this annotation is called when String is used to receive data in excel date format. Refer to java. text. SimpleDateFormat for value NumberFormat digital conversion, using String to receive data in excel digital format will call this annotation. Refer to java. text. DecimalFormat for value inside @ ExcelIgnoreUnannotated by default, those without ExcelProperty annotations will participate in reading and writing, but those with ExcelProperty annotations will not participate

3. Dependence


  <!-- easyexcel  Mainly dependent    This 1 One is basically enough -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>easyexcel</artifactId>
   <version>2.1.4</version>
</dependency>
    <!-- servlet-api -->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.47</version>
</dependency>

STEP 4 Listen


/**
 * EasyExcel  Import listening 
 */
public class ExcelListener extends AnalysisEventListener {
    // You can get this value through an instance 
    private List<Object> datas = new ArrayList<Object>();

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        datas.add(o);// Data is stored to list For batch processing or subsequent business logic processing. 
        doSomething(o);// Deal with according to your own business 
    }

    private void doSomething(Object object) {
        //1 Inbound call interface 
    }

    public List<Object> getDatas() {
        return datas;
    }

    public void setDatas(List<Object> datas) {
        this.datas = datas;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // datas.clear();// Finish parsing and destroy unused resources 
    }
}

5. Interface import Excel


try {
            // Get the file name 
            String filename = file.getOriginalFilename();
            // Get file stream 
            InputStream inputStream = file.getInputStream();
            // Instantiation implements the AnalysisEventListener Class of interface 
            ExcelListener listener = new ExcelListener();
            // Pass in parameters 
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
            // Read information 
            excelReader.read(new Sheet(1, 0, Test.class));
            // Get data 
            List<Object> list = listener.getDatas();
            if (list.size() > 1) {
                for (int i = 0; i < list.size(); i++) {
                    Testobj = (Test) list.get(i);
                    JSONObject jo = new JSONObject();
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

6. Interface export Excel (HttpServletResponse response, HttpServletRequest request)


try {
    String filenames = "111111";
    String userAgent = request.getHeader("User-Agent");
    if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
        filenames = URLEncoder.encode(filenames, "UTF-8");
    } else {
        filenames = new String(filenames.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setContentType("application/vnd.ms-exce");
    response.setCharacterEncoding("utf-8");
    response.addHeader("Content-Disposition", "filename=" + filenames + ".xlsx");
    EasyExcel.write(response.getOutputStream(), Test.class).sheet("sheet").doWrite(testList);
} catch (Exception e) {
}

7. Local import, local export


List<Test> testList = new ArrayList<>();
try {
    String strUrl = "C:\\Users\\Administrator\\Desktop\\json.xlsx";
    File multipartFile = new File(strUrl);
    InputStream inputStream = new FileInputStream(multipartFile);
    // Instantiation implements the AnalysisEventListener Class of interface 
    ExcelListener listener = new ExcelListener();
    // Pass in parameters 
    ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
    // Read information 
    excelReader.read(new Sheet(1, 0, Test.class));
    // Get data 
    List<Object> list = listener.getDatas();
    if (list.size() > 1) {
        for (int i = 0; i < list.size(); i++) {
            Testobj = (Test) list.get(i);
        }
    }
} catch (Exception e) {
    System.out.println(e.getMessage());
}
try {
    String strUrl = "C:\\Users\\Administrator\\Desktop\\json"+System.currentTimeMillis()+".xlsx";
    EasyExcel.write(strUrl,Test.class).sheet("sheet").doWrite(testList);
} catch (Exception e) {
}

The above is the basic use process of EasyExcel. Welcome to praise and pay attention to communication.

The above is the SpringBoot integration EasyExcel step details, more about SpringBoot integration EasyExcel information please pay attention to other related articles on this site!


Related articles: