Usando POI para ler arquivos xls

Ola pessoal

Estou tentando usar a API POI para fazer leitura de um arquivo extenso que tenho em excel (xls) e gostaria primeiramente de ler todo o arquivo e imprimir no console mais nao estou conseguindo. segue o codigo :

Nao entendo pq mais tem um metodo (linha 34) no codigo cell.getCellNum() que nao existe, oque eu poderia usar?
Estou usando esse codigo como exemplo do proprio site.

package br.com.globalcode.util;

import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.ss.usermodel.*;

public class LeitorArquivos {

    public static void main(String[] args) throws IOException, InvalidFormatException {

        Workbook wb = null;
        Row row = null;
        Cell cell = null;
        String path = "/home/daniel/Desktop/OOP/AGENDA TELEFÔNICA/AGENDA TELEFÔNICA.xls";


        InputStream inp = new FileInputStream(path);

        wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);

        System.out.println("Quantidade de linhas : " + sheet.getLastRowNum());

        for (int i = 0; i < 4; i++) {

            for (int j = 0; j < 3; j++) {
                
                CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
                System.out.print(cellRef.formatAsString());
                System.out.print(" - ");

                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        System.out.println(cell.getRichStringCellValue().getString());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            System.out.println(cell.getDateCellValue());
                        } else {
                            System.out.println(cell.getNumericCellValue());
                        }
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.println(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        System.out.println(cell.getCellFormula());
                        break;
                    default:
                        System.out.println();
                }
            }

        }

    }
}

Obrigado.

fiz um teste com a ultima versão do POI e funcionou. esse exemplo deve ser da versão antiga.

Troque as interfaces Cell, Row e WorkBook pelos tipos específicos. São neles é que estão definidos os métodos que vc está usando.

[code]
public static void main(String[] args) throws IOException, InvalidFormatException {

    HSSFWorkbook wb = null;
    HSSFRow row = null;
    HSSFCell cell = null;
    String path = "/home/daniel/Desktop/OOP/AGENDA TELEFÔNICA/AGENDA TELEFÔNICA.xls";


    InputStream inp = new FileInputStream(path);

    wb = new HSSFWorkbook(inp);
    HSSFSheet sheet = wb.getSheetAt(0);

    System.out.println("Quantidade de linhas : " + sheet.getLastRowNum());

    for (int i = 0; i < 4; i++) {

        for (int j = 0; j < 3; j++) {
            
            CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
            System.out.print(cellRef.formatAsString());
            System.out.print(" - ");

            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_STRING:
                    System.out.println(cell.getRichStringCellValue().getString());
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        System.out.println(cell.getDateCellValue());
                    } else {
                        System.out.println(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    System.out.println(cell.getCellFormula());
                    break;
                default:
                    System.out.println();
            }
        }

    }

}[/code]

Ola mario,

Valeu realmente agora aquele metodo funciona, mas o codigo ainda nao esta correto, nao esta saindo no console
voce ou alguem tem ideia do que possa ser?

esta dando esse erro:

Quantidade de linhas : 1028
Exception in thread "main" java.lang.NullPointerException
        at br.com.globalcode.util.LeitorArquivos.main(LeitorArquivos.java:36)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

da uma debugada, podem ser várias coisas. por exemplo, o sheet.getLastRowNum() nem sempre retorna a ultima célula real da planilha. se vc editar a ultima linha, e depois apagar, ele vai contar essa linha tbm, mesmo ela não tendo nada. Com isso alguns métodos de HSSFCell retornam null, e é ai q vc pode ta tomando o npe. ou ainda, o objeto cell pode estar null tbm, dependendo de qual é aultima linha apontada no arquivo

Ola,

Beleza, valeu ai ja ajudou bastante vou dar uma debugada aqui.

Flw.

Ola mario

Ja descobri o que era, minha estrutura de repeticao que tava errada, o certo eh assim :


        HSSFSheet sheet = wb.getSheetAt(0);
        for (Iterator rit = (Iterator) sheet.rowIterator(); rit.hasNext();) {
            row = (HSSFRow) rit.next();
            for (Iterator cit = (Iterator) row.cellIterator(); cit.hasNext();) {
                cell = (HSSFCell) cit.next();

                CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());

                System.out.print(cellRef.formatAsString());
                System.out.print(" - ");

                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_STRING:
                        System.out.println(cell.getRichStringCellValue().getString());
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            System.out.println(cell.getDateCellValue());
                        } else {
                            System.out.println(cell.getNumericCellValue());
                        }
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        System.out.println(cell.getBooleanCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        System.out.println(cell.getCellFormula());
                        break;
                    default:
                        System.out.println();


                }
            }

        }

Vlw ai. Falou.

Curiosidade, esse DateUtil ai, é uma classe sua?

Ela nao eh minha nao, ela eh deste pacote do POI (org.apache.poi.ss.usermodel.DateUtil).

Olá Daniel, teria como você passar o link de onde está esse exemplo que você citou na primeira postagem do tópico?

Abraço!

Ola Vingdel,

Claro, o site da API POI eh esse : http://poi.apache.org/

E o exemplo que voce pediu esta nesse link abaixo :

http://poi.apache.org/spreadsheet/quick-guide.html#Iterator

Flw.

Retomando este tópico… Eu estou conseguindo abrir e manipuar o arquivo XLS normalmente…
A nova pergunta é… tem como eu abrir XLS com senha? Ou seja, o arquivo tem celulas protegidas e preciso acessá-las…

Até +…

Cara, quando eu utilizei a POI, conseguia ler dados da planilha protegida, agora se o arquivo estivesse com senha na abertura, era impossível, não sei se implementaram algo de novo na biblioteca.

O seu problema é na abertura de um arquivo com senha ou é pra pegar o valor das células protegida por senha?

Cara, na verdade é só para pegar o valor. Na abertura está liberado !