POI Excel 가져오기

7463 단어
개인적인 체험으로 말하자면 가져오는 것이 내보내는 것보다 간단하다.
가져오기 전에 데이터를 텍스트 형식으로 가져와야 한다는 것을 설명해야 합니다.
ExcelUtil 클래스
package me.cf81.onestep.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
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.ss.usermodel.CellType;
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 java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @Author: yh
 * @Description: Excel 
 * @Date: Created in 9:44  2018/6/29.
 */

public class ExcelUtils {

    public static  List toList(String path, Class clazz, ExcelFieldMap[] fields, int headerRows) throws IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        if (StringUtils.equals(FilenameUtils.getExtension(path), "xls")) {
            return xlsToList(new FileInputStream(path), clazz, fields, headerRows);
        } else {
            return xlsxToList(new FileInputStream(path), clazz, fields, headerRows);
        }
    }


    public static class ExcelFieldMap {
        private int excelColumn;
        private String fieldName;

        public ExcelFieldMap(int excelColumn, String fieldName) {
            this.excelColumn = excelColumn;
            this.fieldName = fieldName;
        }

        public String getFieldName() {
            return fieldName;
        }

        public void setFieldName(String fieldName) {
            this.fieldName = fieldName;
        }

        public int getExcelColumn() {
            return excelColumn;
        }

        public void setExcelColumn(int excelColumn) {
            this.excelColumn = excelColumn;
        }
    }


    private static  List xlsToList(InputStream inputStream, Class clazz, ExcelFieldMap[] fields, int headerRows) throws IOException, IllegalAccessException, InstantiationException, InvocationTargetException {
        HSSFWorkbook wb = new HSSFWorkbook(inputStream);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;
        Iterator rows = sheet.rowIterator();
        List list = new ArrayList<>();
        for (int i = 0; rows.hasNext(); i++) {
            row = (HSSFRow) rows.next();
            if (i <= headerRows) {
                continue;
            }
            T obj = clazz.newInstance();
            for (ExcelFieldMap excelFieldMap : fields) {
                cell = row.getCell(excelFieldMap.excelColumn);
                if (cell == null) {
                    continue;
                }
                if (cell.getCellTypeEnum() == CellType.STRING) {
                    BeanUtils.setProperty(obj, excelFieldMap.fieldName,  cell.getStringCellValue());
                } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                    BeanUtils.setProperty(obj, excelFieldMap.fieldName, (int)cell.getNumericCellValue());
                } else {
                }
            }

            list.add(obj);
        }
        return list;
    }

    private static  List xlsxToList(InputStream inputStream, Class clazz, ExcelFieldMap[] fields, int headerRows) throws IOException, IllegalAccessException, InstantiationException, InvocationTargetException {
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row;
        XSSFCell cell;
        Iterator rows = sheet.rowIterator();
        List list = new ArrayList<>();
        for (int i = 0; rows.hasNext(); i++) {
            row = (XSSFRow) rows.next();
            if (i <= headerRows) {
                continue;
            }
            T obj = clazz.newInstance();
            for (ExcelFieldMap excelFieldMap : fields) {
                cell = row.getCell(excelFieldMap.excelColumn);
                if (cell == null) {
                    continue;
                }
                if (cell.getCellTypeEnum() == CellType.STRING) {
                    BeanUtils.setProperty(obj, excelFieldMap.fieldName, cell.getStringCellValue());
                } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                    BeanUtils.setProperty(obj, excelFieldMap.fieldName, (int) cell.getNumericCellValue());
                } else {
                    //U Can Handel Boolean, Formula, Errors
                }
            }
            list.add(obj);
        }
        return list;
    }
}


impl 구현 클래스
 /**
     *  excel
     *
     * @param file
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(MultipartFile file,WebSessionUser webSessionUser) throws Exception {
        filePath = FiledExcelPath + UpLoad.upLoadFile(file, FiledExcelPath);
        Long companyId = webSessionUser.getCompanyId();
        List configurations =
            ExcelUtils.toList(new File(filePath).getCanonicalPath(),
                              CarseriesConfiguration.class,
                              new ExcelUtils.ExcelFieldMap[]{
                new ExcelUtils.ExcelFieldMap(0, "carMaterialCode"),
                new ExcelUtils.ExcelFieldMap(1, "carMaterialName"),
                new ExcelUtils.ExcelFieldMap(2, "countryArea"),
                new ExcelUtils.ExcelFieldMap(3, "configName"),
        }, 0);
        // 
        Util.sublist(configurations, l -> carseriesConfigurationMapper.insertAll(l, companyId));
    }

Util.sublist는 데이터베이스에 분할 삽입된 바퀴입니다.
package me.cf81.onestep.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Author: yh
 * @Description:
 * @Date: Created in 9:44  2018/6/29.
 * @Modified By:
 */

public class Util {
    /**
     *  list, 
     *
     * @param list  
     * @param consumer jav8 
     * @param  
     */
    public static  Integer sublist(List list, Consumer> consumer) {
        // 
        return sublist(list, consumer, 5000);
    }

    public static  Integer sublist(List list, Consumer> consumer, int pageSize) {
        Integer count = 0;
        if (list.size() == 0) {
            return count;
        }
        if (list.size() < pageSize) {
            consumer.accept(list);
            count = list.size();
        } else {
            int page = list.size() / pageSize;
            int lave = list.size() % pageSize;
            page = (lave != 0) ? page + 1 : page;
            for (int i = 1; i <= page; i++) {
                int start = (i-1) * (pageSize);
                int end = (i == page) ? start+lave : pageSize+start;
                List current = list.subList(start, end);
                consumer.accept(current);
                count = end;
            }
        }
        return count;
    }
}

좋은 웹페이지 즐겨찾기