Apache POI 之 初学实战篇 (六) --- 读取Excel内容

初学实战篇

读取Excel内容

  • 取Excel中的数值
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("wb8.xls"));
Workbook wb = new HSSFWorkbook(fs.getRoot(), true);

for (Sheet sheet : wb) {
    for (Row row : sheet) {
        for (Cell cell : row) {
            //取数值
            double value = cell.getNumericCellValue();
            System.out.println(value);
        }
    }
}

fs.close();

通用方法:

/**
 * 输出单元格中的内容
 * @param cell
 */
private static void outCellValue(Cell cell) {
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:                      
        System.out.println(
                    cell.getRichStringCellValue().getString());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
                System.out.println(cell.getDateCellValue());
        } else {
            //处理手机号
            DecimalFormat format = new DecimalFormat("#########");
                System.out.println(
                format.format(cell.getNumericCellValue()));

        }
            break;

    case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cell.getBooleanCellValue());
            break;
    case Cell.CELL_TYPE_FORMULA:
            System.out.println(cell.getCellFormula());
            break;
    default:
            System.out.println();
            break;
    }
}
  • 使用MissingCellPolicy控制Null和空格
OPCPackage pkg = OPCPackage.open(new File("IP.xlsx"));
Workbook wb = new XSSFWorkbook(pkg);
Sheet sheet = wb.iterator().next();

int rowStart = Math.min(2, sheet.getFirstRowNum());
int rowEnd = Math.max(200, sheet.getLastRowNum());

for (int rowNum = rowStart; rowNumif (row == null)
        continue;

    int lastCol = Math.max(row.getLastCellNum(), 20);

    for (int colNum=0; colNumif (cell == null) {
            continue;
        } else {
            CellReference cellRef = new CellReference(cell);
                    System.out.print(cellRef.formatAsString());
            System.out.print(" - ");

            outCellValue(cell);
        }
    }
}

pkg.close();
  • 取Excel中的数值
public static void main(String[] args) throws Exception {
    OPCPackage pkg = OPCPackage.open(new File("IP.xlsx"));
    Workbook wb = new XSSFWorkbook(pkg);

    for (Sheet sheet : wb) {
        for (Row row : sheet) {
            for (Cell cell : row) {
                CellReference cellRef = new CellReference(cell);
                System.out.print(cellRef.formatAsString());
                System.out.print(" - ");
                outCellValue(cell);
            }
        }
    }
    pkg.close();
}

你可能感兴趣的:(poi)