Android使用POI读取Excel(XLS和XLSX)

第一步、添加依赖

// Excel
implementation 'org.apache.poi:poi:3.17'
implementation 'org.apache.poi:poi-ooxml:3.17'
implementation 'org.apache.xmlbeans:xmlbeans:3.1.0'
implementation 'stax:stax:1.2.0'

第二步、在程序中使用

private void readExcel(String fileName) {
    try {
        InputStream inputStream = new FileInputStream(fileName);
        Workbook workbook;
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else {
            return;
        }
        Sheet sheet = workbook.getSheetAt(0);
        int rowsCount = sheet.getPhysicalNumberOfRows();
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        for (int r = 0; r < rowsCount; r++) {
            Row row = sheet.getRow(r);
            CellValue v0 = formulaEvaluator.evaluate(row.getCell(0));
            CellValue v1 = formulaEvaluator.evaluate(row.getCell(1));
            Log.i("Excel", "readExcel: " + v0.getStringValue() + "," + v1.getStringValue());
        }
        workbook.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

发表评论