码迷,mamicode.com
首页 > 其他好文 > 详细

封装poi导入篇

时间:2018-11-25 17:50:23      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:esc   ble   ext   int   close   foreach   user   with   for   

前言

有封装的想法好久了,项目中有不少地方需要使用导入功能,导入虽说不能,但是每次都要为了特定类写一个特定方法,很麻烦,我很讨厌一直写这种东西了,正好趁着这次机会就写一个可以解决这种问题的小项目。

maven

 <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.0.0</version>
        </dependency>
<dependency>

基础工具类

package cc.vvxtoys.vhelper.excelhelper.util;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;

public class LoaderUtil {
    
    public static String getValue(Cell cell) {
        switch (cell.getCellType()) {
        case BOOLEAN:
            return String.valueOf(cell.getBooleanCellValue()).trim();
        case NUMERIC:
            if(HSSFDateUtil.isCellDateFormatted(cell)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return String.valueOf(sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()))).trim();
            }
            BigDecimal bd = new BigDecimal(String.valueOf(cell.getNumericCellValue()).trim());
            return bd.toPlainString();
        default:
            return String.valueOf(cell.getStringCellValue()).trim();
        }
    }
    // 空行
    public static boolean isBlank(Row row) {
        for (int i = 0; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }
    
    public static boolean isEmpty(Object obj) {
        if (obj instanceof Cell) {
            Cell cell = (Cell) obj;
            return getValue(cell) == null || "".equals(getValue(cell));
        }
        return obj == null || obj.toString().trim().equals("");
    }
}

实体

package cc.vvxtoys.vhelper.excelhelper.loader;

import java.lang.reflect.Array;
import java.util.stream.BaseStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author vvxtoys
 * @date 2018年10月30日上午11:34:23
 * @Description: TODO
 * @version V1.0
 */
public class ExcelLoader<T> {

    private int version;        //excel版本
    private Class<T> clazz;     //解析类型 javaben或者map
    private String path;        //路径
    private int startRow;       //解析开始条数
    private int endRow;         //解析结束条数
    private int[] indexs;       //对应列下标
    private String[] colums;    //列名
    private String sheetName;   //工作表名
    private int sheetIndex;     //工作表下标
    private int sheetMaxIndex;  //最大工作表下标
    

    public static class Builder<T> {
        private int version;
        private Class<T> clazz;
        private String path;
        private int startRow;
        private int endRow;
        private int[] indexs;
        private String[] colums;
        private String sheetName;
        private int sheetIndex  = -1;//默认值
        private int sheetMaxIndex;

        public Builder(String path){
            verifyPath(path);
        }
        
        public Builder(Class<T> clazz, String path) {
            this.clazz = clazz;
            verifyPath(path);
        }
        public void verifyPath(String path){
            this.path = path;
            if(path.endsWith(".xlsx")){
                this.version = 1;
            }else if(path.endsWith(".xls")){
                this.version = 0;
            }else{
                throw new IllegalArgumentException("path is unavailable!");
            }
        }
        
        public Builder<T> setStartRow(int startRow){
            this.startRow = startRow;
            return this;
        }
        
        public Builder<T> setEndRow(int endRow){
            this.endRow = endRow;
            return this;
        }
        
        public Builder<T> setIndexs(int[] indexs){
            this.indexs = indexs;
            return this;
        }
        
        public Builder<T> setColums(String[] colums){
            this.colums = colums;
            return this;
        }
        
        public Builder<T> setSheetName(String sheetName){
            this.sheetName = sheetName;
            return this;
        }
        
        public Builder<T> setSheetIndex(int sheetIndex){
            this.sheetIndex = sheetIndex;
            return this;
        }
        
        public Builder<T> setSheetMaxIndex(int sheetMaxIndex){
            this.sheetMaxIndex = sheetMaxIndex;
            return this;
        }
        
                                    
        public ExcelLoader<T> builder() {
            if(endRow == 0){
                endRow = version == 0?65535:1048575;//对应xls、xlsx
            }
            return new ExcelLoader<T>(this);
        }

    }
    private ExcelLoader(Builder<T> builder) {
        this.clazz = builder.clazz;
        this.path = builder.path;
        this.version = builder.version;
        this.colums = builder.colums;
        this.indexs = builder.indexs;
        this.sheetName = builder.sheetName;
        this.startRow = builder.startRow;
        this.endRow = builder.endRow;
        this.sheetMaxIndex = builder.sheetMaxIndex;
        this.sheetIndex = builder.sheetIndex;
    }   
    private void generatorColums(int len){
        colums = new String[len];
        //1.8
        IntStream.range(0,len).forEach(i -> Array.set(colums, i, "C"+i));
        //1.7
//      for(int i=0;i<len;i++){
//          colums[i] = "C"+i;
//      }
    }   
    private void generatorIndexs(int len){
        //1.8
        indexs = IntStream.range(0, len).toArray();
        //1.7
//      indexs = new int[len];
//      for(int i=0;i<len;i++){
//          indexs[i] = i;
//      }
    }   
    public void generator(int len){
        if (this.indexs == null) {
            generatorIndexs(len);
        }
        if(this.colums == null){
            generatorColums(len);
        }
    }   
    public String getPath(){
        return this.path;
    }
    public int getVersion() {
        return version;
    }
    public int getStartRow() {
        return startRow;
    }
    public int getEndRow() {
        return endRow;
    }
    public int[] getIndexs() {
        return indexs;
    }
    public String[] getColums() {
        return colums;
    }
    public String getSheetName() {
        return sheetName;
    }
    public int getSheetIndex() {
        return sheetIndex;
    }
    public int getSheetMaxIndex() {
        return sheetMaxIndex;
    }
    
    public Class<T> getClazz() {
        return clazz;
    }
    public int parserType(){
        if(this.clazz == null){
            return 0;//转换为map
        }
        return 1;//转换为javabean
    }
}

处理类

package cc.vvxtoys.vhelper.excelhelper.loader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cc.vvxtoys.vhelper.common.utils.BeanUtil;
import cc.vvxtoys.vhelper.excelhelper.util.LoaderUtil;

public class Loader<T> {

    private ExcelLoader<T> el;

    public Loader(ExcelLoader<T> el) {
        this.el = el;
    }

    public List<?> parsingExcel() {
        if (el.getVersion() == 0) {
            return parsingExcelByXls();
        } else {
            return parsingExcelByXlsx();
        }
    }

    /**
     * @author vvxtoys
     * @date 2018年11月1日上午10:26:01
     * @Description: 解析优先级 
     * 1.sheetName sheet页名 
     * 2.index sheet下标 
     * 3.maxindex sheet最大下标
     */
    private List<?> parsingExcelByXls() {
        List<T> list = new ArrayList<T>();// bean list
        List<Map<String, Object>> resultList = new ArrayList<>();// map list
        HSSFWorkbook workbook = null;
        try {
            int maxIndex = el.getSheetMaxIndex();// sheet页最大下标
            int index = el.getSheetIndex();// sheet页下标
            InputStream is = new FileInputStream(el.getPath());
            workbook = new HSSFWorkbook(is);
            HSSFSheet sheet = null;
            int len = 0;// 自动生成数组参数
            int sheetMaxNumber = workbook.getNumberOfSheets();// sheet个数
            if (el.getSheetName() != null) {
                sheet = workbook.getSheet(el.getSheetName());
                maxIndex = 1;// 不用遍历所有sheet页
            } else if (index != -1) {
                if (index < 0 || index > sheetMaxNumber) {
                    throw new IndexOutOfBoundsException("index is out of bounds");
                }
                sheet = workbook.getSheetAt(index);
                maxIndex = 1;
            } else {
                if (maxIndex < 1) {
                    maxIndex = 1;
                } else if (maxIndex > sheetMaxNumber) {
                    maxIndex = sheetMaxNumber;
                }
            }

            if (el.getColums() == null || el.getIndexs() == null) {
                int startRow = el.getStartRow();
                int startIndex = 0;
                if (startRow <= 0) {
                    startIndex = 0;
                } else {
                    startIndex = startRow - 1;
                }
                if (sheet == null) {
                    len = workbook.getSheetAt(0).getRow(startIndex).getPhysicalNumberOfCells();
                } else {
                    len = sheet.getRow(startIndex).getPhysicalNumberOfCells();
                }
                if (len == 0) {
                    throw new IllegalArgumentException("start column is blank");
                }
                el.generator(len);
            }

            for (int s = 0; s < maxIndex; s++) {
                if (sheet == null) {
                    sheet = workbook.getSheetAt(s);
                }
                int sheetMaxRow = sheet.getLastRowNum();// 行数
                int startRow = el.getStartRow();
                int endRow = el.getEndRow();
                int startIndex = 0;
                int endIndex = 0;
                if (startRow <= 0) {
                    startIndex = 0;
                } else {
                    startIndex = startRow - 1;
                }
                if (endRow > sheetMaxRow) {
                    endIndex = sheetMaxRow + 1;
                } else {
                    endIndex = endRow;
                }
                for (int rowNum = startIndex; rowNum < endIndex; rowNum++) {
                    HSSFRow row = sheet.getRow(rowNum);
                    if (LoaderUtil.isBlank(row)) {// 空行
                        continue;
                    }
                    Map<String, Object> result = new HashMap<>();
                    for (int i = 0; i < el.getColums().length; i++) {
                        HSSFCell cell = row.getCell(el.getIndexs()[i]);
                        if (!LoaderUtil.isEmpty(cell)) {
                            result.put(el.getColums()[i], LoaderUtil.getValue(cell));
                        }
                    }
                    resultList.add(result);
                }
            }

            if (el.parserType() == 0) {
                return resultList;
            } else {
                Class<T> clazz = el.getClazz();
                for (Map<String, Object> m : resultList) {
                    list.add(BeanUtil.mapToBean(m, clazz));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
        
//      finally {
//          if (workbook != null) {
//              try {
//                  workbook.close();
//              } catch (IOException e) {
//                  e.printStackTrace();
//              }
//          }
//      }

        return list;
    }

    private List<?> parsingExcelByXlsx() {
        List<T> list = new ArrayList<T>();// bean list
        List<Map<String, Object>> resultList = new ArrayList<>();// map list
        XSSFWorkbook workbook = null;
        try {
            int maxIndex = el.getSheetMaxIndex();// sheet页最大下标
            int index = el.getSheetIndex();// sheet页下标
            InputStream is = new FileInputStream(el.getPath());
            workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = null;
            int len = 0;// 自动生成数组参数
            int sheetMaxNumber = workbook.getNumberOfSheets();// sheet个数
            if (el.getSheetName() != null) {
                sheet = workbook.getSheet(el.getSheetName());
                maxIndex = 1;// 不用遍历所有sheet页
            } else if (index != -1) {
                if (index < 0 || index > sheetMaxNumber) {
                    throw new IndexOutOfBoundsException("index is out of bounds");
                }
                sheet = workbook.getSheetAt(index);
                maxIndex = 1;
            } else {
                if (maxIndex < 1) {
                    maxIndex = 1;
                } else if (maxIndex > sheetMaxNumber) {
                    maxIndex = sheetMaxNumber;
                }
            }

            if (el.getColums() == null || el.getIndexs() == null) {
                int startRow = el.getStartRow();
                int startIndex = 0;
                if (startRow <= 0) {
                    startIndex = 0;
                } else {
                    startIndex = startRow - 1;
                }
                if (sheet == null) {
                    len = workbook.getSheetAt(0).getRow(startIndex).getPhysicalNumberOfCells();
                } else {
                    len = sheet.getRow(startIndex).getPhysicalNumberOfCells();
                }
                if (len == 0) {
                    throw new IllegalArgumentException("start column is blank");
                }
                el.generator(len);
            }
            for (int s = 0; s < maxIndex; s++) {
                if (sheet == null) {
                    sheet = workbook.getSheetAt(s);
                }
                int sheetMaxRow = sheet.getLastRowNum();// 行数
                int startRow = el.getStartRow();
                int endRow = el.getEndRow();
                int startIndex = 0;
                int endIndex = 0;
                if (startRow <= 0) {
                    startIndex = 0;
                } else {
                    startIndex = startRow - 1;
                }
                if (endRow > sheetMaxRow) {
                    endIndex = sheetMaxRow + 1;
                } else {
                    endIndex = endRow;
                }
                for (int rowNum = startIndex; rowNum < endIndex; rowNum++) {
                    XSSFRow row = sheet.getRow(rowNum);
                    if (LoaderUtil.isBlank(row)) {// 空行
                        continue;
                    }
                    Map<String, Object> result = new HashMap<>();
                    for (int i = 0; i < el.getColums().length; i++) {
                        XSSFCell cell = row.getCell(el.getIndexs()[i]);
                        if (!LoaderUtil.isEmpty(cell)) {
                            result.put(el.getColums()[i], LoaderUtil.getValue(cell));
                        }
                    }
                    resultList.add(result);
                }
            }

            if (el.parserType() == 0) {
                return resultList;
            } else {
                Class<T> clazz = el.getClazz();
                for (Map<String, Object> m : resultList) {
                    list.add(BeanUtil.mapToBean(m, clazz));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

}

beanUtil

public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        T obj = null;
        try{
            obj = clazz.newInstance();
            BeanUtils.populate(obj, map);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

调用类

package cc.vvxtoys.vhelper.excelhelper;

import java.util.List;

import cc.vvxtoys.vhelper.excelhelper.loader.ExcelLoader;
import cc.vvxtoys.vhelper.excelhelper.loader.Loader;
import cc.vvxtoys.vhelper.excelhelper.loader.ExcelLoader.Builder;

public class ExcelLoaderHelper{
    
    Builder<?> builder;
    
    public ExcelLoaderHelper(String path) {
        builder = new Builder<>(path);
    }
    
    public ExcelLoaderHelper(String path,Class<?> clazz) {
        builder = new Builder<>(clazz, path);
    }
    
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:06:18
     * @Description: 设置起始行
     * @param startRow 
     */
    public void setStartRow(int startRow){
        builder.setStartRow(startRow);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:07:02
     * @Description: 设置结束行
     * @param endRow 
     */
    public void setEndRow(int endRow){
        builder.setEndRow(endRow);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:07:40
     * @Description: 指定列下标
     * @param indexs
     */
    public void setIndexs(int[] indexs){
        builder.setIndexs(indexs);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:08:08
     * @Description: 设置列名
     * @param colums
     * @return
     */
    public void setColums(String[] colums){
        builder.setColums(colums);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:09:08
     * @Description: 根据sheet名读取
     * @param sheetName
     */
    public void setSheetName(String sheetName){
        builder.setSheetName(sheetName);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:09:25
     * @Description: 读取指定下标sheet
     * @param sheetIndex
     * @return
     */
    public void setSheetIndex(int sheetIndex){
        builder.setSheetIndex(sheetIndex);
    }
    /**
     * @author vvxtoys
     * @date   2018年11月2日上午10:10:34
     * @Description: 设置可读取最大sheet页
     * @param sheetMaxIndex
     */
    public void setSheetMaxIndex(int sheetMaxIndex){
        builder.setSheetMaxIndex(sheetMaxIndex);
    }
    
    
    @SuppressWarnings("rawtypes")
    public List<?> loadExcelToMap(){    
        ExcelLoader<?> el = builder.builder();
        Loader loader = new Loader<>(el);
        return loader.parsingExcel();
    }
    @SuppressWarnings({"rawtypes"})
    public List<?> loadExcelToBean(){
        ExcelLoader<?> el = builder.builder();
        if(el.getClazz() == null){
            throw new IllegalArgumentException("cannot be cast to NULL");
        }
        Loader loader = new Loader<>(el);
        return loader.parsingExcel();
    }
}

封装poi导入篇

标签:esc   ble   ext   int   close   foreach   user   with   for   

原文地址:https://www.cnblogs.com/vvxtoys/p/exporthelper.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!