Ler Planilha Excel XLSX (2010) com POI

Pessoal,

Apesar de antigo no Fórum, fiquei muitos anos sem programar Java, mas por necessidade de um projeto, estou fazendo uma pequena aplicação que precisa ler uma planilha Excel.

Eu instalei a API POI, mas '~ao a santo que me faça ler uma planilha.

Alguém pode me ajudar??? Estou a dias pesquisando e tentando.

Fiz o seguinte:

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.Iterator;

try
{
FileInputStream arquivo = new FileInputStream(caminhoArquivo);
XSSFWorkbook planilha = new XSSFWorkbook(arquivo);

O problema é que a linha “XSSFWorkbook planilha = new XSSFWorkbook(arquivo);” está dando o seguinte erro:

HTTP Status 500 - Servlet execution threw an exception


type Exception report

message Servlet execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet execution threw an exception

root cause

java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
CITIXLSX.doPost(CITIXLSX.java:115)
CITIXLSX.doGet(CITIXLSX.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
CITIXLSX.doPost(CITIXLSX.java:115)
CITIXLSX.doGet(CITIXLSX.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.32 logs.

Falta um Jar (ou mais), é isso?

Se falta um jar eu não sei. Mas o java compila, acho que se faltasse um jar não compilaria.

Se alguém conseguir postar um exemplo seria muito bom.

Talvez este link te ajude.

http://www.byiorio.com/wordpress/2011/12/14/manipulando-uma-planilha-excel-no-java/

Eu acho que está faltando bibliotecas no seu projeto.
No meu projeto estou usando as bibliotecas poi-3.9, poi-ooxml-3.9, poi-ooxml-schemas-3.9 e xmlbeans-2.5.
E o código que eu usei como base é esse aqui:

package testesexcel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/*import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;*/

public class TestesExcel {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){
        // TODO code application logic here

        //usando SS.model
         try {
            //FileInputStream file = new FileInputStream("Teste 2010.xlsx");
             File file = new File("arquivo");
             String name = file.toString();
             int pos = name.lastIndexOf('.');
             String ext = name.substring(pos + 1);
             FileInputStream fileIn = new FileInputStream(file);
             Workbook obj = null;
             if (ext.equals("xlsx")) {
                try {
                    //Metodo aceita o path do arquivo
                    obj = new XSSFWorkbook(fileIn);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
             } else if (ext.equals("xls")) {
                try {
                    //Metodo nao aceita string do path do arquivo
                    obj = new HSSFWorkbook(fileIn);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
             }
             else
             {
                 throw new IllegalArgumentException("Received file does not have a standard excel extension.");
             }
             int o = 0;
            Sheet worksheet = obj.getSheet("Plan1");
            Row row;
            Cell cell;
            for(int i=0;i<=worksheet.getLastRowNum();i++){
                row = worksheet.getRow(i);
                String linha = "";
                for(int j =0;j<2;j++){
                    cell = row.getCell(j);
 
                   if(cell.getCellType()==1)
                    linha += " | "+ cell.getStringCellValue();
                   else{
                       double aux = 0;
                       int aux2 =0;
                       aux = cell.getNumericCellValue();
                       aux2 = (int) aux;
                       linha += " | " + aux2;
                   }
               }
                
                System.out.println(linha);
            }  

        } catch (FileNotFoundException ex) {
            System.out.println("Arquivo não encontrado");
        }

Vê se isso pode te ajudar.

2 curtidas

Bom dia, xandelol eu coloquei seu codigo exatamente e as bibliotecas exatamentes q vc postou mas ele continua dando erro de biblioteca, tentei a biblioteca poi-3.7 e alguns imports aceitaram mas o restante nao consegui… tem alguma dica?

Obrigada.

camility,

A minha classe que exporta para arquivo do excel tem os seguintes imports:

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Dande obrigada. eu consegui resolver. Os aquivos vieram zipados com extensao jar ai nao importava as bibliotecas ai acabei descobrindo e descompactei. ai consegui trazer a planilha para a jtable, só q tem um problema… quando uma celula do excel esta vazia, eu faço a importação p jtable aquela coluna em vez de preencher vazio ela pula pra proxima, inserindo o valor da celula posterior no lugar da coluna q deveria receber vazio.

Vcs saberiam como resolver?


[code]public void importarXlsx() {

    int i = 0;
    Detalhamento detalhe = new Detalhamento();
    InputStream ExcelFileToRead = null;
    try {
        ExcelFileToRead = new FileInputStream(txtCaminho.getText());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(IFrmDetalhes.class.getName()).log(Level.SEVERE, null, ex);
    }
    XSSFWorkbook wb = null;
    try {
        wb = new XSSFWorkbook(ExcelFileToRead);
    } catch (IOException ex) {
        Logger.getLogger(IFrmDetalhes.class.getName()).log(Level.SEVERE, null, ex);
    }

    XSSFWorkbook test = new XSSFWorkbook();

    XSSFSheet sheet = wb.getSheetAt(0);
    XSSFRow row;
    XSSFCell cell;
    Cell celula;

    Iterator rows = sheet.rowIterator();

    while (rows.hasNext()) {
        row = (XSSFRow) rows.next();
        Iterator cells = row.cellIterator();
        String[] linha = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

        while (cells.hasNext()) {
            cell = (XSSFCell) cells.next();

            if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                if (cell.getColumnIndex() == 7) {
                    linha[i] = "0";
                }
                //System.out.print(cell.getStringCellValue() + "");
                if (cell.getRow() == null || cell.getRow().equals("")) {

                    System.out.print("achou vazio");
                } else {
                    linha[i] = cell.getStringCellValue();
                }
            } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                //System.out.print(cell.getNumericCellValue() + " ");
                if (cell.getNumericCellValue() + "" == null) {
                    linha[i] = "0";
                    System.out.println(cell.getNumericCellValue());
                } else {
                    linha[i] = cell.getNumericCellValue() + "";
                }

            } else {
                linha[i] = "0";
                System.out.println("linha vazia " + i);
            }
            i++;
        }

        //System.out.println();
        i = 0;
        modelo.addRow(linha);
    }
}[/code]

exemplo do codigo…

Olá

O valor da cell está “3200623325” mais quando eu vou ler o campo o valor esta “3.200623325E9”.

Alguém pode me ajudar?

anderson, cmg quando acontece isso, geralmente ja vem do proprio arquivo, ai eu altero la e resolve.
isso ocorre pq o numero é mto grande, deixa ele no excel como texto.

@andersonsrsilva
Pra resolver o caso da notação científica, faça isto:

double aux = 0;
long aux2 =0;
aux = cell.getNumericCellValue();
aux2 = (long) aux;
System.out.println(String.valueOf(aux2));

Eu acho que ele já resolveu isso há 3 anos atrás :joy: