# 读取


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
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.text.SimpleDateFormat;

public class ReadExcel {
    public static void main(String[] args) {
        try (XSSFWorkbook workbook = new XSSFWorkbook("D:\\excelDemo\\b.xlsx")) {

            //获取指定sheet,也可以获取全部
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            //最后一行下标,注意表头(如果有表头的话,没有就不需要 +1)会占一行,需要加 1 ,不然会少一行数据
            int lastRowNum = sheetAt.getLastRowNum() + 1;
            //获取行和单元格
            for (int i = 0; i < lastRowNum; i++) {
                //获取行
                XSSFRow row = sheetAt.getRow(i);
                //最后一列
                short lastCellNum = row.getLastCellNum();

                StringBuilder stringBuilder = new StringBuilder();

                for (int j = 0; j < lastCellNum; j++) {
                    //获取每个单元格
                    XSSFCell cell = row.getCell(j);
                    //获取单元格内容
                    Object cellValue = getCellValue(cell);
                    stringBuilder.append(cellValue).append('\t');
                }
                System.out.println(stringBuilder);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Object getCellValue(Cell cell) {
        //获取单元格数据类型
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case STRING:
                return cell.getStringCellValue();
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //日期类型
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
                } else {
                    //数字
                    return cell.getNumericCellValue();
                }
            case FORMULA:
                //表达式
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}