Apache POI读取Excel工具类

依赖
    <!-- POI -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.1.2</version>
    </dependency>

    <!-- POI-ooxml -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.2</version>
    </dependency>
工具类
/**
 * 封装Apache的POI工具类
 * <p>
 * 主要功能:读取Excel,获取文件内容
 * </p>
 *
 * @author ACE_GJH
 * @date 2020/11/20
 */
public class ApachePoiUtil {

    private static final Logger log = LoggerFactory.getLogger(ApachePoiUtil.class);

    /**
     * 读取Excel内容
     *
     * @param fileName 文件名
     * @param inputStream 文件输入流
     * @param sheetName 工作表名
     * @param startRow 开始行数
     * @param endRow 结束行数
     * @param startCol 开始列数
     * @param endCol 结束列数
     * @return 行列集合
     * @throws IOException
     */
    public static List<String[]> readExcel(String fileName, InputStream inputStream, String sheetName, Integer startRow, Integer endRow, Integer startCol, Integer endCol) throws IOException {
        //Excel文件类型检验,并获取工作簿对象
        Workbook workbook = getWorkbook(fileName, inputStream);
        if (workbook == null) {
            inputStream.close();
            throw new IOException("The file name suffix is not .xls or .XLSX or .xls or .XLSX");
        }
        //读取工作表
        Sheet sheet = workbook.getSheet(sheetName);
        //确定行数
        int lastRowNum = sheet.getLastRowNum();
        if (startRow == null || startRow < 0) {
            startRow = 0;
        }
        if (startRow > lastRowNum) {
            workbook.close();
            return null;
        }

        if (endRow == null) {
            endRow = lastRowNum;
        }
        if(endRow < startRow) {
            workbook.close();
            return null;
        }else {
            endRow = Math.min(lastRowNum, endRow);
        }
        //确定列数
        if (startCol == null || startCol < 0) {
            startCol = 0;
        }
        if (endCol == null || endCol < startCol) {
            workbook.close();
            throw new IOException("endCol is illegal");
        }

        int length = endCol - startCol + 1;
        //获取数据
        ArrayList<String[]> rows = new ArrayList<>(length * 4 / 3);
        for (Integer i = startRow; i <= endRow; i++) {
            //获取第i行数据
            Row row = sheet.getRow(i);
            String[] cols = new String[length];
            for (int j = startCol; j <= endCol; j++) {
                Cell cell = row.getCell(j);
                cols[j] = getContentByCellType(cell);
            }
            rows.add(cols);
        }

        workbook.close();
        return rows;
    }

    /**
     * 根据单元格类型获取单元格内容
     *
     * @param cell Excel单元格
     * @return
     */
    private static String getContentByCellType(Cell cell) {
        String value = null;
        switch (cell.getCellType()) {
            //数字
            case NUMERIC:
                //如果为时间格式的内容
                if (DateUtil.isCellDateFormatted(cell)) {
                    //注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    value = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                    break;
                } else {
                    value = Double.toString(cell.getNumericCellValue());
                }
                break;
                //字符串
            case STRING:
                value = cell.getStringCellValue();
                break;
                //Boolean
            case BOOLEAN:
                value = Boolean.toString(cell.getBooleanCellValue());
                break;
                //公式
            case FORMULA:
                value = cell.getCellFormula();
                break;
                //空值
            case BLANK:
                break;
                //非法字符
            case ERROR:
                break;
                //未知字符
            default:
                break;
        }
        return value;
    }

    /**
     * 判断是否是03的excel: .xls .XLS
     */
    private static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /**
     * 判断是否是07的excel: .xlsx .XLSX
     */
    private static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 获取工作簿对象
     */
    private static Workbook getWorkbook(String fileName, InputStream inputStream) throws IOException {
        if (isExcel2007(fileName)) {
            return new XSSFWorkbook(inputStream);
        }
        if (isExcel2003(fileName)) {
            return new HSSFWorkbook(inputStream);
        }
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭建華

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值