最近遇到一个对我来说比较棘手的问题,通过java代码实现读取Execle中的数据存到MAP<String,List<Object(实体类中)>>,虽然不难,但是很久不写,感觉比较生疏,因此将写好的代码分享给大家,以供参考,如有什么问题和好的建议热烈欢迎评论区留言,共同探讨,共同进步。
public static Map<String,List<ExecleEntity>> read(String path) {
File file = new File(path);
InputStream inputStream = null;
Workbook workbook = null;
//List<String> list1 = new ArrayList<String>();
String str = "";
try {
//判断文件是否是Execle
inputStream = new FileInputStream(file);
//判断Excel的版本
workbook = WorkbookFactory.create(inputStream);
inputStream.close();
//工作表对象
Sheet sheet = workbook.getSheetAt(0);
//总行数
int rowLength = sheet.getLastRowNum();
//工作表的列
Row row = sheet.getRow(0);
//总列数
int colLength = row.getLastCellNum();
//得到指定的单元格
Cell cell = row.getCell(0);
//得到单元格样式
CellStyle cellStyle = cell.getCellStyle();
//new HashMap将读取execle循环出的值存进Map中。
map = new HashMap<String,List<ExecleEntity>>();
//根据行读取列数据,存到Map中。 for (int i = 2; i < rowLength; i++) {
row = sheet.getRow(i);
ExecleEntity entity = new ExecleEntity();
entity.setTestCase(row.getCell(0).getStringCellValue());
entity.setType(row.getCell(1).getStringCellValue());
entity.setElement(row.getCell(2).getStringCellValue());
entity.setAction(row.getCell(3).getStringCellValue());
entity.setText(row.getCell(4).getStringCellValue());
entity.setType1(row.getCell(5).getStringCellValue());
entity.setElement1(row.getCell(6).getStringCellValue());
entity.setAction1(row.getCell(7).getStringCellValue());
entity.setText1(row.getCell(8).getStringCellValue());
entity.setExpectValuel(row.getCell(9).getStringCellValue());
//如果key在MAP中存在,将value值set进map中。
if(map.containsKey(row.getCell(0).getStringCellValue())) {
List<ExecleEntity> list = map.get(row.getCell(0).getStringCellValue());
list.add(entity);
map.put(""+row.getCell(0).getStringCellValue()+"", list);
}else {
List<ExecleEntity> list = new ArrayList<ExecleEntity>();
list.add(entity);
map.put(""+row.getCell(0).getStringCellValue()+"", list);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}