使用poi读取上传的Excel文件,并将数据封装到java对象中

使用poi读取Excel文件,并将数据封装到java对象中

    • Maven引入依赖
    • Excel工具类

Maven引入依赖

        <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>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.1</version>
        </dependency>
    </dependencies>

Excel工具类

/**
 * @author Ingcom
 */
public class ExcelUtil {
    /**
     *
     * @param clazz 封装的class对象
     * @param cellNameList cell的名字集合字符串,用 “,” 分割
     * @param file  上传的文件
     * @param  封装的类型
     * @return List
     */
    public <T> List<T> importExcel(Class<T> clazz, String cellNameList, MultipartFile file){
        InputStream inputStream = null;
        Workbook workbook = null;

        //文件名
        String filename = file.getOriginalFilename();
        //fieldName集合
        List<String> fieldNameList = Arrays.asList(cellNameList.split(","));

        //返回的数据集合
        List<T> dataList = new ArrayList<>();

        try {
            inputStream = file.getInputStream();

            //根据文件类型确定具体的workbook
            String suffix = "xlsx";
            String drop = ".";
            if (suffix.equals(StringUtils.substringAfterLast(filename,drop))){
                workbook = new XSSFWorkbook(inputStream);
            }else{
                workbook = new HSSFWorkbook(inputStream);
            }

            //默认获取第一个sheet,名字为"sheet1"
            Sheet sheet = workbook.getSheet("sheet1");

            int rowNo = 0;
            for (Row row : sheet) {

                //Excel第一行一般为字段描述,不是数据直接跳过,同时判断每行的第一个cell是否为空,如果为空就认定当前行没有数据直接跳过
                if (rowNo++ == 0 || StringUtils.isBlank(row.getCell(0).toString())){
                    continue;
                }

                //创建封装对象
                T t = clazz.newInstance();

                //获取对象的field数组,并将其封装成map
                Field[] fields = clazz.getDeclaredFields();
                Map<String, Field> map = Arrays.stream(fields).collect(Collectors.toMap(c -> c.getName(), c -> c));

                int cellNo = 0;
                for (Cell cell : row) {
                    //设置格式,解决读取乱码
                    cell.setCellType(CellType.STRING);
                    //获取cell值,注意去除前后空格
                    String cellString = cell.toString().trim();

                    //根据fieldName获取field
                    String fieldName = fieldNameList.get(cellNo++);
                    Field field = map.get(fieldName);

                    field.setAccessible(true);

                    //将cell值转化为封装对象字段属性的值
                    Class<?> type = field.getType();
                    Object convert = ConvertUtils.convert(cellString, type);

                    //封装field的值
                    field.set(t,convert);

                    field.setAccessible(false);
                }
                dataList.add(t);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {    
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return dataList;
    }
}

你可能感兴趣的:(使用poi读取上传的Excel文件,并将数据封装到java对象中)