package com.it.excel.excelLearn; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtil { public static List<ExcelSheetStructure> readExcel(String filePath) throws IOException { InputStream is = null; XSSFWorkbook xssfWorkbook = null; List<ExcelSheetStructure> sheetsDate = null; // 流读取Excel入内存 is = new FileInputStream(filePath); xssfWorkbook = new XSSFWorkbook(is); sheetsDate = new ArrayList<>(); // 遍历 for (Sheet sheet : xssfWorkbook) { ExcelSheetStructure sheetStructure = new ExcelSheetStructure(); // 获取sheet名字 String sheetName = sheet.getSheetName(); sheetStructure.setSheetName(sheetName); // 获取有效数据,开始行和结束行 int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); // 读取数据 List<Map<String, Object>> notHeaderList = new ArrayList<>(); for (int i = firstRowNum; i <= lastRowNum; i++) { Row row = sheet.getRow(i); if (row == null) { break; } // 处理表头一行数据 if (i == firstRowNum) { Map<String, Object> headerRowMap = getHeaderRowData(row); sheetStructure.setSheetTableHeaderDate(headerRowMap); } else { // 非表头数据 Row headerRow = sheet.getRow(firstRowNum); Map<String, Object> notHeaderRowMap = getNotHeaderRowData(row, headerRow); notHeaderList.add(notHeaderRowMap); } } sheetStructure.setSheetTableList(notHeaderList); // 判断当前sheet是否有数据,如果没有,就打印sheetName,否则加入Excel数据结构中 if (!sheetStructure.getSheetTableList().isEmpty() && !sheetStructure.getSheetTableHeaderDate().isEmpty()) { sheetsDate.add(sheetStructure); } else { System.out.println(sheetStructure.getSheetName()); } } xssfWorkbook.close(); is.close(); return sheetsDate; } private static Map<String, Object> getNotHeaderRowData(Row row, Row headerRow) { Map<String, Object> rowMap = new HashMap<>(); for (Cell cell : row) { /** * 设置单元格的类型是String,防止读取数据方法getStringCellValue()报错 * 如果单元格中数据格式是数字类型:Cannot get a STRING value from a NUMERIC cell */ cell.setCellType(CellType.STRING); String cellValue = cell.getStringCellValue(); int columnIndex = cell.getColumnIndex(); Cell currentHeaderCell = headerRow.getCell(columnIndex); // 存储:Map<"当前单元格对应的表头中文","当前单元格值"> rowMap.put(currentHeaderCell.getRichStringCellValue().toString(), cellValue); } return rowMap; } private static Map<String, Object> getHeaderRowData(Row row) { Map<String, Object> headerMap = new HashMap<>(); for (Cell cell : row) { cell.setCellType(CellType.STRING); String cellValue = cell.getStringCellValue(); int columnIndex = cell.getColumnIndex(); headerMap.put(String.valueOf(columnIndex), cellValue); } return headerMap; } }