NullPointerException when using getSheet ()

1

I am trying to edit an excel file with apache poi in the following way:

 public void generarOrdenDePago(Cliente cliente, Periodo periodo, OutputStream outputStream) {

    try {
        InputStream in = new FileInputStream("ordenPagoLimpia.xls");
        try (Workbook wb = WorkbookFactory.create(in)) {
            Sheet sheet = wb.getSheet("MySheet");
            Row row = sheet.createRow(15);  //El error sale aquí

            Cell cell = row.createCell(2);
            cell.setCellValue("nonononono");

            wb.write(outputStream);
        }
        outputStream.flush();
        outputStream.close();

    } catch (IOException ex) {
        System.out.println(ex);
    } catch (EncryptedDocumentException | InvalidFormatException ex) {
        Logger.getLogger(IGenerarOrdenPagoExcelFedex.class.getName()).log(Level.SEVERE, null, ex);
    }
}

However, when executing the following line: Row row = sheet.createRow(15);

the system throws me a nullPointerException, but could not understand why.

This is the excel I'm trying to edit:

    
asked by gibran alexis moreno zuñiga 30.03.2017 в 21:33
source

2 answers

1

The problem is that the sheet I want to edit is not called "MySheet", but "report", then it is solved in the following way:

Sheet sheet = wb.getSheet("reporte");
    
answered by 30.03.2017 / 21:54
source
1

You could use the index of the sheet (sheet), always starting at 0.

Sheet sheet = wb.getSheetAt(0);

you can be sure there is at least one page:

if (wb.getNumberOfSheets() > 0) {
        Sheet sheet = wb.getSheetAt(0);
}
    
answered by 21.09.2018 в 21:11