JAVA project combat - Alibaba easyexcel Export Import tool use

This section will share to you, to achieve the export and import of Excel tables, easy to use plug-ins.

 

package com.sf.vsolution.hb.sfce.util.excel;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 阿里巴巴EasyExcel工具
 * @author: zhucj
 * @date: 2019-11-05 13:22
 */
public class EasyExcelUtils {

    private static finalLoggerFactory.getLogger Logger = Logger (EasyExcelUtils. Class ); 

    Private  static Sheet initSheet; 

    static { 
        initSheet = new new Sheet (. 1, 0 ); 
        initSheet.setSheetName ( "Sheet" );
         // set the width adaptive 
        initSheet.setAutoWidth (Boolean. TRUE); 
    } 

    / ** 
     * introducing 
     * less than 1000 rows default style 
     * @param filePath file absolute path 
     * @return 
     * / 
    public  static List <Object> readLessThan1000Row (String filePath) {
         returnreadLessThan1000RowBySheet (filePath, null ); 
    } 

    / ** 
     * introducing 
     * less than 1000 rows of data with style 
     * @param filePath file absolute path 
     * @param Sheet 
     * @return 
     * / 
    public  static List <Object> readLessThan1000RowBySheet (String filePath, Sheet Sheet) {
         IF (! ) {StringUtils.hasText (filePath)
             return  null ; 
        } 

        Sheet = Sheet =! null ? Sheet: initSheet; 

        the inputStream inputStream =null ;
         the try { 
            inputStream = new new ; the FileInputStream (filePath)
             return EasyExcelFactory.read (inputStream, Sheet); 
        } the catch (a FileNotFoundException E) { 
            logger.error ( "file path or file not found error" , E); 
        } the finally {
             the try {
                 IF (inputStream =! null ) { 
                    inputStream.close (); 
                } 
            } the catch (IOException E) { 
                logger.error ("excel file read failed, failure reason: {}" , E); 
            } 
        } 
        return  null ; 
    } 

    / ** 
     * introducing 
     * default style data line is greater than 1000 
     * @param filePath 
     * @return 
     * / 
    public  static List <Object> readMoreThan1000Row (String filePath) {
         return readMoreThan1000RowBySheet (filePath, null ); 
    } 

    / ** 
     * import 
     * is more than 1000 rows custom styles 
     * @param filePath 
     * @param Sheet 
     * @return
     */
    public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet) {
        if (!StringUtils.hasText(filePath)) {
            return null;
        }
        sheet = sheet != null ? sheet : initSheet;

        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            ExcelListener excelListener = new ExcelListener();
            EasyExcelFactory.readBySax (inputStream, Sheet, excelListener); 
            return excelListener.getDatas (); 
        } the catch (a FileNotFoundException E) { 
            logger.error ( "file path or file not found error" ); 
        } the finally {
             the try {
                 IF (inputStream! = null ) { 
                    inputStream.close (); 
                } 
            } the catch (IOException E) { 
                logger.error ( "Excel file read failed, failure reason: {}" , E); 
            } 
        } 
        return  null ; 
    } 

    / ** 
     * exporting a single sheet
     * @Param the Response 
     * @param dataList 
     * @param Sheet 
     * @param fileName 
     * @throws UnsupportedEncodingException
      * / 
    public  static  void writeExcelOneSheet (HttpServletResponse the Response, List <? The extends BaseRowModel> dataList, Sheet Sheet, String fileName) {
         IF (CollectionUtils.isEmpty (dataList)) {
             the throw  new new a RuntimeException ( "derived data table is empty!" ); 
        } 
        // if the sheet is empty, the default 
        IF (null == sheet) {
            sheet = initSheet;
        }
        try {
            String value = "attachment; filename=" + new String(
                    (fileName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", value);

            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = EasyExcelFactory.getWriter(out, ExcelTypeEnum.XLSX, true);
            // 设置属性类
            sheet.setClazz(dataList.get(0).getClass());
            writer.write(dataList, sheet);
            writer.finish();
            out.flush();
        } catch (IOException e) {
            logger.error("导出失败,失败原因:{}", e);
        }
    } 

    / ** 
     * @author Lockie 
     * @Description export excel table deriving a plurality of support sheet 
     * @Param the OutputStream output stream 
     * Map <String, List> sheetName each sheet data 
     * ExcelTypeEnum type are to be exported excel ExcelTypeEnum.xls and have ExcelTypeEnum.xlsx 
     * @date 12:16 aM 2019/1/31 
     * / 
    public  static  void writeExcelMutilSheet (HttpServletResponse the Response, the Map <String, List <? the extends BaseRowModel >> dataList, String fileName) throws UnsupportedEncodingException {
         IF (CollectionUtils.isEmpty (dataList)) {
             the throw  new new a RuntimeException ( "derived data table is empty!" ); 
        }
         the try { 
            String value= "attachment; filename=" + new String(
                    (fileName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", value);
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            // 设置多个sheet
            setMutilSheet(dataList, writer);
            writer.finish();
            out.flush();
        } catch (IOException e) {
            logger.error("导出异常", e);
        }
    }


    /**
     * @Author lockie
     * @Description //setSheet数据
     * @Date 上午12:39 2019/1/31
     */
    private static void setMutilSheet(Map<String, List<? extends BaseRowModel>> dataList, ExcelWriter writer) {
        int sheetNum = 1;
        for (Map.Entry<String, List<? extends BaseRowModel>> stringListEntry : dataList.entrySet()) {
            Sheet sheet = new Sheet(sheetNum, 0, stringListEntry.getValue().get(0).getClass());
            sheet.setSheetName(stringListEntry.getKey());
            writer.write(stringListEntry.getValue(), sheet);
            sheetNum++;
        }
    }


    /**
     * 导出监听
     */
    @Data
    public static classExcelListenerthe extends AnalysisEventListener {
         Private List <Object> = DATAS new new the ArrayList <> (); 

        / ** 
         * Progressive parsing 
         * @param data object in the current row 
         * @param analysisContext
          * / 
        @Override 
        public  void Invoke (Object object, AnalysisContext analysisContext) {
             IF (Object =! null ) { 
                datas.add (Object); 
            } 
        } 


        / ** 
         * this method is called after all the data has been parsed 
         * @param analysisContext
         */
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        }
    }

}

 

package com.sf.detectprocess.controller.param.export;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.sf.detectprocess.core.constant.SystemConstants;
import lombok.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @description: 导出订单信息
 * @author: zhucj
 * @date: 2019-11-05 15:48
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ExportComeInsureInfo extends{BaseRowModel 


    @ExcelProperty (value = "order number", index = 0 )
     Private String orderNo; 

    @ExcelProperty (value = "line generation time", index =. 1, the format = SystemConstants.DEFAULT_DATETIME_FORMAT)
     Private a Date createTime; 

    @ExcelProperty (value = "shipment date", index = 2 )
     Private String comeTime; 

    @ExcelProperty (value = "item name", index =. 3 )
     Private String goodsInfo; 

    @ExcelProperty (value = "number of packages", index =. 4 )
     Private Integer countPack; 

    @ ExcelProperty (value = "starting point"index = 5)
    private String comeSendAddress;

    @ExcelProperty(value = "终点",index = 6)
    private String comeConsignAddress;

    @ExcelProperty(value = "单号",index = 7)
    private String waybillNo;

    @ExcelProperty(value = "声明价值",index = 8)
    private BigDecimal sumInsureValue;

}
        <!--alibaba导出 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>1.1.2-beta5</version>
        </dependency>

 

 

 

Guess you like

Origin www.cnblogs.com/zhucj-java/p/12017940.html