The article directories

      • The introduction
      • Gracefully read Excel
      • Write gracefully in Excel
      • Elegant summary
      • A little attention, won’t get lost

The introduction

EasyExcel is the best Excel export tool at present. This article will lead you to use EasyExcel gracefully in background development.

Gracefully read Excel

Background interfaces that read documents typically use the type MultipartFile from which an InputStream can be constructed. To read Excel with EasyExcel, you need to construct a listener first. Luffy has prepared it for you:

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/ * * *@author Carson
 * @date2020/6/4 21:26 * /
public class ExcelReaderListener<T> extends AnalysisEventListener<T> {
    /** * The data set returned */
    private List<T> list = new ArrayList<>(1 << 6);

    /** * If spring is used, use this constructor. Each time you create a Listener, you need to pass in the Spring-managed classes */
    public ExcelReaderListener(a) {}/ * * * the each data parsing would call for * *@paramThe data data *@paramContext Excel reads the context */
    @Override
    public void invoke(T data, AnalysisContext context) {
        System.out.printf("Parse to a single data :{%s}", JSON.toJSONString(data));
        System.out.println();
        list.add(data);
    }

    /** * when all data is parsed, call **@paramContext Excel reads the context */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {}public List<T> getList(a) {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list; }}Copy the code

After creating the listener, you need to manually write a tool class, specially used to read Excel, Shaoxia here prepared two reading methods:

import com.alibaba.excel.EasyExcel;

import java.io.InputStream;
import java.util.List;

/ * * *@author Carson
 * @date 2020/6/4 21:31
 */
public class ExcelReaderUtil<T> {
    private Class<T> clazz;

    public ExcelReaderUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public List<T> readByStream(InputStream inputStream) {
        ExcelReaderListener<T> readerListener = new ExcelReaderListener<>();
        EasyExcel.read(inputStream, clazz, readerListener).sheet().doRead();
        return readerListener.getList();
    }

    public List<T> readByPath(String fileName) {
        ExcelReaderListener<T> readerListener = new ExcelReaderListener<>();
        EasyExcel.read(fileName, clazz, readerListener).sheet().doRead();
        returnreaderListener.getList(); }}Copy the code

Note: the code here is generic, feel don’t want to look at the past can be directly copied to use.

Now that the basic reading utility class has been implemented, the template class has been created. What is a template class? It is a class that has different parameters for each Excel header, and each parameter is qualified with the @ExcelProperty annotation.

@Data
public class GoodsReaderModel {
    @ ExcelProperty (SKU "goods")
    public Long skuId;

    @ExcelProperty(" Event Start Time ")
    public String startTime;

    @ExcelProperty(" Event End Time ")
    public String finishTime;
}
Copy the code

Then read from the interface:

    @RequestMapping(value = "/import", method = RequestMethod.POST, produces = {"application/json; charset=UTF-8"})
    @apiOperation (value = "import commodity information ", httpMethod = "POST", notes =" import commodity information ")
    @ResponseBody
    public List<GoodsReaderModel > importGoodsFromExcel(@RequestParam("excel") MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile == null) {
            LOGGER.info("Entered Excel information is empty");
            return null;
        }
        ExcelReaderUtil<GoodsReaderModel> excelReader = new ExcelReaderUtil<>(GoodsReaderModel.class);
        List<GoodsReaderModel> modelList = Lists.newArrayList();
        try {
            InputStream inputStream = multipartFile.getInputStream();
            modelList = excelReader.readByStream(inputStream);
        } catch (IOException e) {
            LOGGER.info("Sorry, no file found.");
            return null;
        }
        // Follow up data processing logic
    }
Copy the code

Write gracefully in Excel

Download Excel in the interface can also be elegant, first attached to the general formatting class:

import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.google.common.collect.Lists;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.ServletOutputStream;
import java.util.List;

/ * * *@author Carson
 * @date 2020/6/5 19:39
 */
public class ExcelWriterUtil {

    public WriteWorkbook workbookGenerator(ServletOutputStream outputStream) {
        WriteWorkbook workbook = new WriteWorkbook();
        workbook.setOutputStream(outputStream);
        workbook.setExcelType(ExcelTypeEnum.XLSX);
        workbook.setNeedHead(true);

        // The header's strategy
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // Set the left alignment of the header
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.getIndex());
        // Content strategy
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // Align the content to the left
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        WriteFont writeFont = new WriteFont();
        writeFont.setFontName("宋体");
        contentWriteCellStyle.setWriteFont(writeFont);
        contentWriteCellStyle.setFillPatternType(FillPatternType.NO_FILL);
        contentWriteCellStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.getIndex());
        // This strategy is header is header style content is content style other strategies can be implemented themselves
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        List<WriteHandler> customWriteHandlerList = Lists.newArrayList();
        customWriteHandlerList.add(horizontalCellStyleStrategy);
        workbook.setCustomWriteHandlerList(customWriteHandlerList);
        returnworkbook; }}Copy the code

The interface request can then be written like this:

   @RequestMapping(value = "export", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8"})
    @apiOperation (value = "data export ", httpMethod = "GET", notes =" data export ")
    @ResponseBody
    public void exportData(a) {
       
              // Get the data according to your actual business. Note that each row is a List
            List<List<String>> resList = Lists.newArrayList();

        try{
            ServletOutputStream outputStream = response.getOutputStream();
           
            WriteWorkbook workbook = new ExcelWriterUtil().workbookGenerator(outputStream);
    
            ExcelWriter writer = new ExcelWriter(workbook);
            String fileName = new String("data");
            response.setHeader("Content-disposition"."attachment; filename=" + fileName + ".xlsx");
            WriteSheet writeSheet = new WriteSheet();
            writeSheet.setSheetName("Data Details");
            writeSheet.setAutoTrim(true);

            writer.write(resList, writeSheet);
            writer.finish();
        } catch (IOException e) {
            LOGGER.error("Abnormal export data", e); }}Copy the code

Elegant summary

EasyExcel is just a tool class, which I feel is much less important than thread pools, message queues, etc., but it’s nice to be able to skillfully use it in development. Personally, this is the most useful and efficient Excel tool class we’ve ever used. Shaoxia has done a test, EasyExcel only needs about 60 seconds to export one million pieces of data (currently Excel can hold up to 1.04 million pieces of data), while the traditional POI technology takes several hours, and the memory optimization is poor, large objects can not be recycled in time, it is easy to cause the JVM FULL GC.

A little attention, won’t get lost