Gabriel Braga
Gabriel Braga

Reputation: 41

Reading a cell from Excel using Apache POI

I'm new to the Apache POI, so I'm having some trouble to use it.

I need to read an Excel file, but I don't need all the rows, because my final goal with this code is to shrink the file (that have over 900 lines) to have only the information I'll use later.

So I tried to use the following code:

public static void main(String[] args) {

    List<Planejado> planejados = new ArrayList<Planejado>();
    int i = 0;
    int linha = 5;

    try{
        FileInputStream fis = new FileInputStream("C:\\Users\\fs0234\\Desktop\\Projetos\\Realizado X Planejado\\Planej. Semanal por CC do Funcionário (20).xls");
        HSSFWorkbook wb = new HSSFWorkbook(fis);
        HSSFSheet sheet = wb.getSheetAt(0);

        int rowMax = sheet.getLastRowNum();

        while (i <= rowMax) { // interação do excel validando pela coluna I

            Row row = sheet.getRow(linha);
            Cell cell = row.getCell(9);



            if (cell.equals("")){   // Line 38  

                Planejado planejado = new Planejado();
                planejado.setCentroCusto("CC - " + i); // obter valor da celula j + contador
                planejado.setNomeRecurso("Recurso " + i); // obter valor da celula k + contador

                for(int j = 1; j < 53; j++) { //interação das colunas w até bw
                    planejado.getTimecard().put("Semana" + j, 40 + j);//obter o valor das horas
                }

                planejados.add(planejado);
            }
            linha++;
            i++;
        }

        for(Planejado planejado : planejados) { 
            //gravar no banco todos os objetos dentro da lista
            System.err.println(planejado.getCentroCusto() + " | " + planejado.getNomeRecurso() + " | " + planejado.getTimecard().get("Semana6"));
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Where I need only the rows where the column 9 is empty.

But I get the Error

"Exception in thread "main" java.lang.NullPointerException at main.PopulaPlanejado.main(PopulaPlanejado.java:38)"

Don't know if it's clear what I need to do, but I hope some of you can help me.

Upvotes: 0

Views: 931

Answers (2)

Gabriel Braga
Gabriel Braga

Reputation: 41

Thank's to you and some other friend I'm was able to solve the problem.

Here is the code without bugs

List<Planejado> planejados = new ArrayList<Planejado>();
        int i = 0;
        int linha = 5;

        try {
            FileInputStream fis = new FileInputStream("C:\\Users\\fs0234\\Desktop\\Projetos\\Realizado X Planejado\\Planej. Semanal por CC do Funcionário (20).xls");
            HSSFWorkbook wb = new HSSFWorkbook(fis);
            HSSFSheet sheet = wb.getSheetAt(0);

            int rowMax = sheet.getLastRowNum();

            while (i <= rowMax) { // Loop até a última linha da planilha

                Row row = sheet.getRow(linha);

                if (row != null) { // Apenas linhas "não nulas"
                    Cell cell = row.getCell(8); // obter valor da celula I

                    if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { //Verifica se a coluna I é nula
                        Cell CC = row.getCell(6); // obter valor da celula G
                        Cell nome = row.getCell(10); // obter valor da celula K

                        Planejado planejado = new Planejado();
                        planejado.setCentroCusto("CC - " + CC);
                        planejado.setNomeRecurso("Recurso - " + nome);

                        for (int j = 1, weekCol = 22; j <= 53; j++, weekCol++) { // Loop para pegar todas as semanas

                            Cell week = row.getCell(weekCol); // Obter valor da coluna da semana

                            if (week != null) {
                                planejado.getTimecard().put("Semana" + j, week.getNumericCellValue());
                            } else {
                                planejado.getTimecard().put("Semana" + j, Double.valueOf(0));
                            }
                        }
                        planejados.add(planejado);
                    }
                }
                linha++;
                i++;
            }

            for (Planejado planejado : planejados) { 
                StringBuffer timecard = new StringBuffer();

                for (int k = 1; k < 53; k++) {
                    timecard.append("Semana " + k);
                    timecard.append(": ");
                    timecard.append(planejado.getTimecard().get("Semana" + k));
                    timecard.append(", ");
                }

                System.err.println(planejado.getCentroCusto() + " | " + planejado.getNomeRecurso() + " | " + timecard.toString());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Upvotes: 0

Rockstar
Rockstar

Reputation: 2288

Instead Of using

if (cell.equals("")){
...
}

Try using this

if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
....
}

While using equals() for object comparison be careful otherwise you'll end up throwing NullPointerException. Do remember that calling any method on a null resulting object will throw a NPE.

You should remember some best practice to avoid NullPointerException.

Bad comparison

 if (state.equals("OK")) {
  ...
}

Better comparison

if ("OK".equals(state)) {
  ...
}

So in the later case you don't have a chance to end up with NPE.

Hope it will help you. :)

Upvotes: 2

Related Questions