package com.baiyz.utils; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map;
@Slf4j public class ReadExcelUtils {
private LinkedList<Map<String, String>> getExcel(String path, String sheetName) throws FileNotFoundException { LinkedList<Map<String, String>> ans = null; try(FileInputStream inputStream = new FileInputStream(new File(path))){ ans = new LinkedList<>(); XSSFWorkbook sheets = new XSSFWorkbook(inputStream); XSSFSheet sheet = sheets.getSheet(sheetName); if (sheet == null){ return new LinkedList<>(); } XSSFRow titleRow = sheet.getRow(0); for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { LinkedHashMap<String, String> rowData = new LinkedHashMap<>(); XSSFRow row = sheet.getRow(i); for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) { XSSFCell cell = row.getCell(j); XSSFCell titleCell = titleRow.getCell(j); cell.setCellType(CellType.STRING); if(cell.getStringCellValue() .equals("")){ continue; } rowData.put(getString(titleCell),getString(cell)); } ans.add(rowData); } }catch (Exception e){ log.info("读取文件出现异常:"+e); } return ans; }
private static String getString(XSSFCell xssfCell) { if (xssfCell == null) { return ""; } if (xssfCell.getCellType() == CellType.NUMERIC) { return String.valueOf(xssfCell.getNumericCellValue()); } else if (xssfCell.getCellType() == CellType.BOOLEAN) { return String.valueOf(xssfCell.getBooleanCellValue()); } else { return xssfCell.getStringCellValue(); } }}
|