package com.yqzx.common.util; import java.io.*; import cn.hutool.core.io.FileUtil; import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 读取Excel * * @author zengwendong */ @Slf4j public class ReadExcelUtils { private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class); private Workbook wb; private Sheet sheet; private Row row; // int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读 // int lastRowIndex = sheet.getLastRowNum(); /** * @Author wh * @Date 2022/6/7 - 9:46 * @Description // * filepath:路径 * firstRowIndex:开始行数从 **/ public static void ReadExcelUtils(String filepath, int firstRowIndex) { try { //String encoding = "GBK"; // File excel = new File(filepath); File excel = FileUtil.touch(filepath); if (excel.isFile() && excel.exists()) { //判断文件是否存在 String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!!!!! Workbook wb; //根据文件后缀(xls/xlsx)进行判断 if ( "xls".equals(split[1])){ FileInputStream fis = new FileInputStream(excel); //文件流对象 wb = new HSSFWorkbook(fis); }else if ("xlsx".equals(split[1])){ wb = new XSSFWorkbook(excel); }else { System.out.println("文件类型错误!"); return; } //开始解析 Sheet sheet = wb.getSheetAt(0); //读取sheet 0 // int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读 int lastRowIndex = sheet.getLastRowNum(); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行 System.out.println("rIndex: " + rIndex); Row row = sheet.getRow(rIndex); if (row != null) { int firstCellIndex = row.getFirstCellNum(); int lastCellIndex = row.getLastCellNum(); for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列 Cell cell = row.getCell(cIndex); if (cell != null) { System.out.println(cell.toString()); } } } } } else { log.info("找不到指定的文件"); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } }