ExcelUtil工具类(XSSFWorkbook读取和写入Excel),入参和出参都是:List<Map<String,Object>>
一、读取Excel
testdata.xlsx
1、new XSSFWorkbook对象
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
2、new XSSFSheet对象
//获取sheet第一个
XSSFSheet xSheet = wb.getSheetAt(0);
if(sheetName!=null) {
//如果sheetName入参可用这个,通过名称获取
xSheet = wb.getSheet(sheetName);
}
3、遍历行读取数据写入List<Map<String,Object>>
for (int i = 0; i <= xSheet.getLastRowNum(); i++) { //遍历所有行
if(i==0){ //标题行
for (int j = 0; j < xSheet.getRow(i).getPhysicalNumberOfCells(); j++) {
headMap.put(j, xSheet.getRow(i).getCell(j).toString());
}
continue;
}
Map<String, Object> paramsMap = new HashMap<>();
for (int j = 0; j < xSheet.getRow(i).getPhysicalNumberOfCells(); j++) { //遍历当前行所有列
String key=headMap.get(j);
Cell cell=xSheet.getRow(i).getCell(j);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
paramsMap.put(key,cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
paramsMap.put(key,new Double(cell.getNumericCellValue()).intValue());