读取Excel文件,用对象接收数据

@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class ExcelUtils {

    /**
     * 读取Excel表格的第一个sheet数据到list, 强制实体类成员变量声明顺序与Excel数据列数据一致
     * @param file MultipartFile
     * @param clazz 数据类的class
     * @return list
     */
    public static  List readFromExcel(MultipartFile file, Class clazz) {

        // 排除掉被@FieldExclude 标记过的Field
        List fields = Arrays.stream(clazz.getDeclaredFields())
                .filter(field -> field.getAnnotation(FieldExclude.class) == null)
                .collect(Collectors.toList());

        List result;
        Sheet sheet;

        try {
            InputStream stream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(stream);

            // 读取Excel第一个sheet
            sheet = workbook.getSheetAt(0);

        } catch (IOException e) {
            log.error("Excel数据读取失败:", e);
            throw new WechatException("Excel数据读取失败");
        }

        // 依赖实体类成员变量的定义顺序
        return IntStream.range(2, sheet.getPhysicalNumberOfRows()).mapToObj(r -> {

            try {
                T object = clazz.newInstance();
                IntStream.range(0, fields.size()).forEach(i -> {

                    try {
                        Field field = fields.get(i);
                        field.setAccessible(true);

                        field.set(object, StringUtils.EMPTY);
                        Cell cell = sheet.getRow(r).getCell(i);
                        if (cell != null) {
                            cell.setCellType(CellType.STRING);
                            field.set(object, cell.getStringCellValue());
                        }
                    } catch (IllegalAccessException e) {
                        log.error("Excel读取到类属性失败:", e);
                    }
                });

                return object;
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("对象初始化失败", e);
            }
            return null;

        }).collect(Collectors.toList());
    }
}

你可能感兴趣的:(java)