基于POI的读取excel的简单工具类

 1 import java.util.ArrayList;
 2 import java.util.LinkedHashMap;
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 public class ExcelModel {
 7     private Map<String, List<List<String>>> sheetMap = new LinkedHashMap<>();
 8 
 9     ExcelModel(){}
10     public List<List<String>> getSheet(String sheetName) {
11         return sheetMap.get(sheetName);
12     }
13 
14     public List<List<String>> getSheet(int sheetIndex) {
15         List<List<List<String>>> lists = new ArrayList<>(sheetMap.values());
16         return lists.get(sheetIndex);
17     }
18 
19     void putSheet(String sheetName, List<List<String>> sheet) {
20         sheetMap.put(sheetName, sheet);
21     }
22 }
//读取后的内容对象,可以根据sheet名字和索引获取想要的sheet
 1 public class ExcelUtil {
 2     public static ExcelModel readExcel(Workbook wb) {
 3         ExcelModel excelModel = new ExcelModel();
 4         wb.forEach(sheet -> {
 5             List<List<String>> sheetData = new ArrayList<>(sheet.getPhysicalNumberOfRows());
 6             sheet.forEach(row -> {
 7                 List<String> rowData = new ArrayList<>(row.getPhysicalNumberOfCells());
 8                 row.forEach(cell -> {
 9                     cell.setCellType(CellType.STRING);
10                     rowData.add(cell.getStringCellValue());
11                 });
12                 sheetData.add(rowData);
13             });
14             excelModel.putSheet(sheet.getSheetName(), sheetData);
15         });
16         return excelModel;
17     }
18 }

//excle读取工具类,使用readExcel方法传入一个workBook对象,返回excelModel实体




posted @ 2020-05-16 11:45  TS小学生  阅读(274)  评论(0)    收藏  举报