POI操作本地excel

public static void checkExcelVaild(File file) throws Exception {
        if (!file.exists()) {
            throw new Exception("文件不存在");
        }
        if (!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))) {
            throw new Exception("文件不是Excel");
        }
    }

    public static void main(String[] args) throws Exception {
        String path = "demo.xlsx";
        List<Object> list = new ArrayList<>();
        try {
            // 同时支持Excel 2003、2007
            File excelFile = new File(path); // 创建文件对象
            FileInputStream in = new FileInputStream(excelFile); // 文件流
            checkExcelVaild(excelFile);
            Workbook workbook = WorkbookFactory.create(in); // 这种方式
            Sheet sheet = workbook.getSheetAt(0); // 遍历第一个Sheet
            Object o = new Object();
            for (Row row : sheet) {
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    int cellType = cell.getCellType();
                    switch (cellType) {
                    case 0:
                        o = cell.getNumericCellValue();
                        break;
                    case 1:
                        o = cell.getStringCellValue();
                        break;
                    case 2:
                        o = cell.getCellFormula();
                        break;
                    case 3:
                        o = "";
                        break;
                    case 4:
                        o = cell.getBooleanCellValue();
                        break;
                    default:
                        // cell.setCellType(1);
                        o = cell.getStringCellValue();
                        break;
                    }
                    //如果要修改笨本地的excel
                    /*cell.setCellValue("");
                    FileOutputStream excelFileOutPutStream = new FileOutputStream(path);// 写数据到这个路径上
                    workbook.write(excelFileOutPutStream);*/
                    list.add(o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

猜你喜欢

转载自blog.csdn.net/MisterMister/article/details/85047465