Java excel upload -- poi

Posted by J4rod on Sun, 01 Dec 2019 05:25:31 +0100

Many batch upload requirements are different in work. Each requirement needs to write a batch upload code, which is too annoying.. Decided to write a general tool, this code copy is ready to use. Please leave a message in the comment area if you need to improve

Method call parameter example:
The fields in the upload file correspond to the properties of the object
String[] fieldsName = new String[]{"carModelName","salePrice"};

This parameter is the property of the object corresponding to the column required field in the upload file
String[] fieldsIsNull = new String[]{"carModelName"};

Note: the order of array properties must be the same as that in the file. When parsing the file, the assignment will not assign wrong fields

 public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
public static final String OFFICE_EXCEL_2007_POSTFIX = "xlsx";
public static final String EMPTY = "";
public static final String POINT = ".";

/
**

 * Data obtained by reflection processing
 * @param
 */
public T reflectDeal(T className, Cell cell, String fieldName){
    Class aClass = null;
    try {
        aClass = className.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields) {
            field.setAccessible(true);
            String names = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
            if(field.getName().equals(fieldName) && field.getType().getName().equals("java.math.BigDecimal")){
                aClass.getMethod("set"+names,BigDecimal.class).invoke(className,new BigDecimal(""+cell));
            }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.String")){
                aClass.getMethod("set"+names,String.class).invoke(className,cell.getStringCellValue().toString());
            }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Integer")){
                aClass.getMethod("set"+names,Integer.class).invoke(className,cell);
            }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Double")){
                aClass.getMethod("set"+names,Double.class).invoke(className,cell);
            }
        }
    }  catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return className;
}

 /**
 * This code parses xls file
 * @param
 */
public List<T> analysisXls(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull)  {
    int totalrows = 0;
    int totalCell = 0;

    List<T> list = new ArrayList();
    logger.info("====================  Start parsing xls file  =========================");
    //Stream read file
    //create a file
    HSSFWorkbook wb = null;
    try {
        wb = new HSSFWorkbook(in);
        //Number of pages read
        for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){
            Sheet xs = wb.getSheetAt(num);
            if(xs == null){
                continue;
            }
            totalrows = xs.getLastRowNum()+1;
            for (int rnum = 1 ; rnum < totalrows ; rnum ++){
                boolean flag = false;
                T o = null;
                try {
                    o = (T)clazz.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Row row = xs.getRow(rnum);
                if(row != null){
                    totalCell = row.getLastCellNum();
                    int nullCellNumb = 0;
                    for (int cnum = 0 ; cnum < totalCell ; cnum ++){
                        Cell cell = row.getCell(cnum);
                        if(null == cell){
                            nullCellNumb++;
                            if(nullCellNumb>=10){
                                break;
                            }
                            continue;
                        }
                        if( cell != null && !"".equals(cell.toString().trim())){
                            this.reflectDeal(o, cell, fieldsName[cnum]);
                        }else {
                            for (int x=0;x<fieldsIsNull.length;x++){
                                if(fieldsIsNull[x].equals(fieldsName[cnum])){
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (flag){
                        continue;
                    }
                    list.add(o);
                }else {
                    return list;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            in.close();
            if(null != wb){
                wb.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return list;
}

/**

 * Code analysis xlsx file
 * @param
 * @param clazz
 * @param fieldsName
 * @return
 */
public List<T> analysisXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull){
    int totalrows = 0;
    int totalCell = 0;
    List<T> list = new ArrayList();
    logger.info("====================  Start parsing xlsx file  =========================");
    //Stream read file
    //create a file
    XSSFWorkbook wb = null;
    try {
        wb = new XSSFWorkbook(OPCPackage.open(in));
        //Number of pages read
        for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){
            Sheet xs = wb.getSheetAt(num);
            if(xs == null){
                continue;
            }
            totalrows = xs.getLastRowNum()+1;
            for (int rnum = 1 ; rnum < totalrows ; rnum ++){
                boolean flag = false;
                T o = (T)clazz.newInstance();
                Row row = xs.getRow(rnum);
                if(row != null){
                    totalCell = row.getLastCellNum();
                    int nullCellNumb = 0;
                    for (int cnum = 0 ; cnum < totalCell ; cnum ++){
                        Cell cell = row.getCell(cnum);
                        if(null == cell){
                            nullCellNumb++;
                            if(nullCellNumb>=10){
                                break;
                            }
                            continue;
                        }

                        if( cell != null  && !"".equals(cell.toString().trim())){
                            nullCellNumb = 0;
                            this.reflectDeal(o, cell, fieldsName[cnum]);
                        }else {
                            for (int x=0;x<fieldsIsNull.length;x++){
                                if(fieldsIsNull[x].equals(fieldsName[cnum])){
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (flag){
                        continue;
                    }
                    list.add(o);
                }else {
                    return list;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        logger.info("======= XSSF Failed to create file ====");
        e.printStackTrace();
    }finally {
        try {
            in.close();
            if(null != wb){
                wb.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return list;
} 

/**

 *This code distinguishes e'xcel Version, which method to call respectively
 * @param
 * @param clazz
 * @param fieldsName
 * @return
 * @throws IOException
 */
public List<T> readxlsAndXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String fileName,String[] fieldsIsNull) {
    if(null != in  ){
        String postfix = ExcelImport.getpostfix(fileName);
        if(OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
            return this.analysisXls(in,clazz,fieldsName,fieldsIsNull);
        }else if(OFFICE_EXCEL_2007_POSTFIX.equals(postfix)){
           return this.analysisXlsx(in,clazz,fieldsName,fieldsIsNull);
        }else {
            return null;
        }
    }
    return null;
} 

/**

 * Get file suffix
 * @param path
 * @return
 */
public static String getpostfix(String path){
    if(path == null || EMPTY.equals(path.trim())){
        return "";
    }
    if(path.contains(POINT)){
       return path.substring(path.lastIndexOf(POINT)+1,path.length());
    }
    return "";
}

Topics: Java