import java package Excel by poi

  When using Excel Apache POI package into rows and columns need to be taken to the corresponding values, it is necessary to know the value of the corresponding column should be stored into that field when the object to the value, change in the table that appears will become troublesome Therefore custom annotations used herein manner, indicating that corresponding attribute in the object header, the header traversal to find the corresponding cell from the program, to facilitate data import.

Required jar with a little bag :( tools, so much introduced two packages)

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>commons-beanutils</groupId>
	<artifactId>commons-beanutils</artifactId>
	<version>1.9.2</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.2.1</version>
</dependency>

  Custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD ,ElementType.TYPE})
public @interface ExcelIn {

    /**
     * Import sheet name
     * @return
     */
    String sheetName() default "";

    /**
     * Corresponding to the header field name
     * @return
     */
    String title() default "";
}

  Import data receiving entity:

@ExcelIn (sheetName = "user information" )
 public  class the UserInfo {
     Private String ID;

    @ExcelIn(title = "姓名")
    private String name;

    @ExcelIn(title = "年龄")
    private Integer age;

    @ExcelIn (title = "Date of Birth" )
     Private a Date Birthday;
}

  Import Excel data:

public class ExcelReader<T> {
    private static BeanUtilsBean beanUtilsBean = new BeanUtilsBean();

    static {
        beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.DateConverter(null), java.util.Date.class);
    }
    /**
     * Where the header names and the corresponding index of the columns, according to the corresponding value taken title
     */
    private final Map<String,Integer> title_to_index = new HashMap<>();
    /**
     * All fields annotated with ExcelIn
     */
    private final List<Field> fields = new ArrayList<>();

    /**
     * Statistical tables of rows and number of columns used to traverse the table
     */
    private  int firstCellNum = 0;
    private  int lastCellNum = 0;
    private  int firstRowNum = 0;
    private  int lastRowNum = 0;

    private String sheetName ;

    private HSSFSheet sheet ;

    public List<T> read(InputStream in , Class clazz) throws Exception {
        gatherAnnotationFields(clazz);
        configSheet(in);
        configHeader();
        List rList= null;
        try {
            rList = read content (Clazz);
        } catch (IllegalAccessException e) {
            throw new Exception(e);
        } catch (InstantiationException e) {
            throw new Exception(e);
        } catch (InvocationTargetException e) {
            throw new Exception(e);
        }
        return rList ;
    }

    private List readContent(Class clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        Object o = null ;
        HSSFRow row = null ;
        List<Object> rsList = new ArrayList<>();
        Object value = null ;
        for(int i = (firstRowNum+1);i<=lastRowNum;i++){
            o = clazz.newInstance();
            row = sheet.getRow(i);
            Cell HSSFCell = null ;
             for (Field, Field: Fields) {
                 // The annotations in the title, to take the column in the table corresponding to the value of the 
                Integer = title_to_index.get column (field.getAnnotation (ExcelIn. Class ) .title ( ));
                 IF (column == null ) {
                     Continue ;
                }
                cell = row.getCell(column);
                value = getCellValue(cell) ;
                if(null != value && StringUtils.isNotBlank(value.toString())) {
                    beanUtilsBean.setProperty(o, field.getName(), value);
                }
            }
            rsList.add(o);
        }
        return rsList ;
    }

    Private  void configSheet (InputStream in) throws Exception {
         // HSSFWorkbook: 97-03 can only create versions of Excel, namely: xls ending Excel
         // want to import the end xlsx of Excel, with XSSFWorkbook 
        the try (HSSFWorkbook wb = new new HSSFWorkbook (in)) {
            getSheetByName(wb);
        } catch (FileNotFoundException e) {
            throw new Exception(e);
        } catch (IOException e) {
            throw new Exception(e);
        }
    }


    /**
     * Get the value corresponding to the ranks based sheet, and the head corresponding to a column value map
     */
    private void configHeader(){
        this.firstRowNum = sheet.getFirstRowNum() ;
        this.lastRowNum = sheet.getLastRowNum() ;
        //第一行为表头,拿到表头对应的列值
        HSSFRow row = sheet.getRow(firstRowNum);
        this.firstCellNum = row.getFirstCellNum();
        this.lastCellNum = row.getLastCellNum();
        for (int i = firstCellNum;i<lastCellNum;i++){
            title_to_index.put(row.getCell(i).getStringCellValue(),i);
        }
    }

    /**
     * Get sheet according to sheet name
     * @param workbook
     * @return
     * @throws Exception
     */
    private void getSheetByName(HSSFWorkbook workbook) throws Exception {
        int sheetNumber = workbook.getNumberOfSheets();
        for (int i = 0; i < sheetNumber; i++) {
            String name = workbook.getSheetName(i);
            if(StringUtils.equals(this.sheetName,name)) {
                this.sheet = workbook.getSheetAt(i);
                return;
            }
        }
        the throw  new new Exception ( "Name not found to excel in" + the this .sheetName + "The Sheet" );
    }

    /**
     * According to custom annotations, get the table you want to import the sheet names and field names to be imported
     * @Param clazz
     * @throws Exception
     */
    private void gatherAnnotationFields(Class clazz) throws Exception {
        if(!clazz.isAnnotationPresent(ExcelIn.class)){
            throw new Exception(clazz.getName()+"类上没有ExcelIn注解");
        }
        ExcelIn ExcelIn = (ExcelIn) clazz.getAnnotation (ExcelIn. Class );
         the this .sheetName = excelIn.sheetName ();
         // get all the fields defined in 
        Field, [] = allFields FieldUtils.getAllFields (clazz);
         // get all field and store in a list 
        for (Field, Field: allFields)
        {
            if (field.isAnnotationPresent(ExcelIn.class))
            {
                fields.add(field);
            }
        }
        IF (fields.isEmpty ()) {
             the throw  new new Exception (clazz.getName () + "No ExcelIn comment field" );
        }
    }

    private Object getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        Object obj = null;
        switch (cell.getCellTypeEnum()) {
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case ERROR:
                obj = cell.getErrorCellValue();
                break;
            case FORMULA:
                try {
                    obj = String.valueOf(cell.getStringCellValue());
                } catch (IllegalStateException e) {
                    obj = numericToBigDecimal(cell);
                }
                break;
            case NUMERIC:
                obj = getNumericValue(cell);
                break;
            case STRING:
                String value = String.valueOf(cell.getStringCellValue());
                value = value.replace(" ", "");
                value = value.replace("\n", "");
                value = value.replace("\t", "");
                obj = value;
                break;
            default:
                break;
        }
        return obj;
    }

    Private Object getNumericValue (the Cell Cell) {
         // transaction date or time format 
        IF (HSSFDateUtil.isCellDateFormatted (Cell)) {
             return   cell.getDateCellValue ();
        } The else  IF (. Cell.getCellStyle () getDataFormat () == 58 ) {
             // handle custom Date format: m d May 1999 (determined by the format of the cell id solution, id value is 58) 
            Double value = Cell .getNumericCellValue ();
             return org.apache.poi.ss.usermodel.DateUtil.getJavaDate (value);
        } else {
            return numericToBigDecimal(cell);
        }
    }

    private Object numericToBigDecimal(Cell cell) {
        String valueOf = String.valueOf(cell.getNumericCellValue());
        BigDecimal bd = new BigDecimal(valueOf);
        return bd;
    }
}

  Test results of the import:

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

    @org.junit.Test
    public void t(){
        try{
            File file = new File("d:/abc.xls");
            ExcelReader<UserInfo> reader = new ExcelReader<>();
            InputStream is = new FileInputStream(file);
            List<UserInfo> list = reader.read(is,UserInfo.class);
            if (CollectionUtils.isNotEmpty(list)) {
                for (UserInfo u : list) {
                    System.out.println ( "Name:" + u.getName () + " , Age:" + u.getAge () + " , Date of Birth:" + u.getBirthday ());
                }
            }
        }catch (Exception e){
            e.printStackTrace ();
        }
    }
}

  Excel data import: (Excel sheet name of the receiving entity object sheetName)

  The results show:

Guess you like

Origin www.cnblogs.com/xiao-OvO-/p/11012989.html