ExcelUtiles.java 2.81 KB
package cn.com.glsx.merchants.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.com.glsx.framework.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

@Slf4j
public class ExcelUtiles {
    /**
     * 转换文件内容为流数据
     *
     * @param content
     * @return
     */
    public static ByteArrayInputStream parseContentToStream(byte[] content) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
        ImportParams parmas = new ImportParams();
        parmas.setNeedVerfiy(true);
        return inputStream;
    }

    /**
     * 校验参数
     *
     * @return
     */
    public static ImportParams verify() {
        ImportParams parmas = new ImportParams();
        parmas.setNeedVerfiy(false);
        return parmas;
    }

    /**
     * 不校验参数
     *
     * @return
     */
    public static ImportParams unVerify() {
        ImportParams parmas = new ImportParams();
        parmas.setNeedVerfiy(false);
        return parmas;
    }

    public static byte[] exportGoodsExcel(List<?> list, Class<?> pojoClass) {
        ExportParams exportParams = new ExportParams();
        exportParams.setCreateHeadRows(true);
        exportParams.setType(ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        byte[] barray = null;
        if (workbook != null) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                barray = bos.toByteArray();
            } catch (Exception e) {
                log.info("excel导出异常===msg:" + e.getMessage());
                throw new ServiceException("excel异常");
            }
        }
        return barray;
    }

    public static <T> ExcelImportResult<T> importExcel(byte[] content, Class<T> pojoClass) {
        ByteArrayInputStream fileInputStream = ExcelUtiles.parseContentToStream(content);
        ExcelImportResult<T> excelModulList = null;
        try {
            excelModulList = ExcelImportUtil.importExcelMore(fileInputStream, pojoClass, ExcelUtiles.verify());
        } catch (Exception e) {
            log.info("excel导入异常===msg:" + e.getMessage());
            throw new ServiceException("excel异常");
        }
        return excelModulList;
    }
}