How to read and write excel file

后端 未结 22 3000
北荒
北荒 2020-11-22 04:49

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to

22条回答
  •  日久生厌
    2020-11-22 05:01

    using spring apache poi repo

    if (fileName.endsWith(".xls")) {
    
    
    
    File myFile = new File("file location" + fileName);
                    FileInputStream fis = new FileInputStream(myFile);
    
                    org.apache.poi.ss.usermodel.Workbook workbook = null;
                    try {
                        workbook = WorkbookFactory.create(fis);
                    } catch (InvalidFormatException e) {
    
                        e.printStackTrace();
                    }
    
    
                    org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
    
    
                    Iterator rowIterator = sheet.iterator();
    
    
                    while (rowIterator.hasNext()) {
                        Row row = rowIterator.next();
    
                        Iterator cellIterator = row.cellIterator();
                        while (cellIterator.hasNext()) {
    
                            Cell cell = cellIterator.next();
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_STRING:
                                System.out.print(cell.getStringCellValue());
                                break;
                            case Cell.CELL_TYPE_BOOLEAN:
                                System.out.print(cell.getBooleanCellValue());
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                System.out.print(cell.getNumericCellValue());
                                break;
                            }
                            System.out.print(" - ");
                        }
                        System.out.println();
                    }
                }
    

提交回复
热议问题