java动态解析excel数据(支持多行嵌套表头)

将excel动态解析成bean,支持多行嵌套式表头,根据表头行数构建entity模板,然后每条数据对模板深拷贝后将参数写入,代码如下:

public static void main(String[] args) {
    File file = new File("xlsxPath");
    List<JSONObject> testEntityList = dr(2, file, new TypeReference<JSONObject>() {});
    System.out.println(JSONObject.toJSONString(testEntityList));
}

public static <T> List<T> dr(int titleRowNum, File excelFile, TypeReference<T> typeReference) {
    ExcelReader excelReader = ExcelUtil.getReader(excelFile);
    int sheetCount = excelReader.getSheetCount();

    List<T> resultList = new ArrayList<>();

    for (int sheetNum = 0; sheetNum < sheetCount; sheetNum++) {
        excelReader.setSheet(sheetNum);
        // 构建表头结构
        List<List<Object>> titleRowsList = excelReader.read(0, titleRowNum - 1);
        List<List<String>> titleColumnList = new ArrayList<>(titleRowsList.get(0).size());
        // 将表头第一行初始化到表头list
        titleRowsList.get(0).forEach(titleRowColumnValue -> {
            List<String> titleColumnValueList = new ArrayList<>();
            titleColumnValueList.add(titleRowColumnValue.toString());
            titleColumnList.add(titleColumnValueList);
        });

        // 拼接表头其他行
        for (int titleRowIndex = 1; titleRowIndex < titleRowsList.size(); titleRowIndex++) {
            List<Object> titleRowList = titleRowsList.get(titleRowIndex);
            for (int rowIndex = 0; rowIndex < titleRowList.size(); rowIndex++) {
                if (!titleRowList.get(rowIndex).toString()
                        .equals(titleColumnList.get(rowIndex).get(titleColumnList.get(rowIndex).size() - 1))) {
                    titleColumnList.get(rowIndex).add(titleRowList.get(rowIndex).toString());
                }
            }
        }

        // 初始化json解析模板
        JSONObject jsonDataTemplate = new JSONObject();
        titleColumnList.forEach(columnList -> {
            if (columnList.size() > 1) {
                for (int columnIndex = 0; columnIndex < columnList.size() - 1; columnIndex++) {
                    jsonDataTemplate.put(columnList.get(columnIndex), new JSONObject());
                }
            }
        });

        // 读取数据
        List<List<Object>> valueRowsList = excelReader.read(titleRowNum);
        valueRowsList.forEach(valueRowList -> {
            JSONObject rowValueJson = JSONObject.parseObject(jsonDataTemplate.toJSONString());
            for (int valueRowIndex = 0; valueRowIndex < valueRowList.size(); valueRowIndex++) {
                List<String> columnTitleList = titleColumnList.get(valueRowIndex);
                if (columnTitleList.size() > 1) {
                    JSONObject tmeJson = rowValueJson;
                    for (int columnTitleIndex = 0; columnTitleIndex < columnTitleList.size(); columnTitleIndex++) {
                        if (columnTitleIndex != columnTitleList.size() - 1) {
                            tmeJson = rowValueJson.getJSONObject(columnTitleList.get(columnTitleIndex));
                        } else {
                            tmeJson.put(columnTitleList.get(columnTitleIndex), valueRowList.get(valueRowIndex));
                        }
                    }
                } else {
                    rowValueJson.put(columnTitleList.get(0), valueRowList.get(valueRowIndex));
                }
            }
            resultList.add(JSON.parseObject(rowValueJson.toJSONString(), typeReference));
        });

    }

    return resultList;
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想使用JavaExcel数据导入到嵌套对象中,可以使用Apache POI和Java反射。 以下是一个示例代码,演示了如何动态填充嵌套对象的属性值: 假设我们有以下两个类: ```java public class Address { private String street; private String city; private String state; private String zipCode; // getters and setters } public class Person { private String name; private int age; private Address address; // getters and setters } ``` 假设我们已经将Excel表格中的数据读入到了一个List<List<String>>对象中,其中每个List<String>对象表示一行Excel数据。下面的代码展示了如何使用反射和Apache POI将数据填充到Person对象中: ```java import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import java.lang.reflect.Field; import java.util.List; public class ExcelReader { public static void main(String[] args) { // 假设我们已经将Excel表格中的数据读入到了一个List<List<String>>对象中 List<List<String>> excelData = getExcelData(); // 创建一个名为"Sheet1"的工作表 Sheet sheet = workbook.getSheet("Sheet1"); // 获取工作表中的数据行 for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { Row row = sheet.getRow(i); // 创建Person对象 Person person = new Person(); // 使用反射获取Person对象中的所有属性 Field[] fields = Person.class.getDeclaredFields(); // 遍历所有属性 for (int j = 0; j < fields.length; j++) { Field field = fields[j]; // 获取属性名 String fieldName = field.getName(); // 获取属性值 Cell cell = row.getCell(j); Object cellValue = null; if (cell != null) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { cellValue = cell.getStringCellValue(); } else if (cellType == CellType.NUMERIC) { cellValue = cell.getNumericCellValue(); } } // 如果属性值为null,则跳过 if (cellValue == null) { continue; } // 如果属性名为address,则填充Address对象的属性值 if (fieldName.equals("address")) { // 创建Address对象 Address address = new Address(); // 获取Address对象中的所有属性 Field[] addressFields = Address.class.getDeclaredFields(); // 遍历所有属性 for (int k = 0; k < addressFields.length; k++) { Field addressField = addressFields[k]; // 获取属性名 String addressFieldName = addressField.getName(); // 获取属性值 Cell addressCell = row.getCell(j + k + 1); Object addressCellValue = null; if (addressCell != null) { CellType addressCellType = addressCell.getCellType(); if (addressCellType == CellType.STRING) { addressCellValue = addressCell.getStringCellValue(); } else if (addressCellType == CellType.NUMERIC) { addressCellValue = addressCell.getNumericCellValue(); } } // 如果属性值为null,则跳过 if (addressCellValue == null) { continue; } // 使用反射设置Address对象的属性值 try { Field addressField = Address.class.getDeclaredField(addressFieldName); addressField.setAccessible(true); addressField.set(address, addressCellValue); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } // 设置Person对象的address属性值 person.setAddress(address); } else { // 使用反射设置Person对象的属性值 try { field.setAccessible(true); field.set(person, cellValue); } catch (IllegalAccessException e) { e.printStackTrace(); } } } // 打印Person对象的属性值 System.out.println(person); } } } ``` 这个示例代码中,我们首先使用反射获取了Person类中的所有属性,然后遍历了Excel表格中的数据行,并使用反射和Apache POI将数据填充到Person对象中。当属性名为address时,我们创建了一个新

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值