0

estoy intentado mejorar el código y una de las mejoras es mostrar todas las filas y columnas menos la primera fila de un excel. Lo que me está funcionando es indicar cuantas filas y columnas tienen datos en un excel para que me permita leérmelas. aquí os dejo el código

public static  List<String> listaDatos = new ArrayList<>();
//Padre con elementos encapsulados
public static List<Data> LISTA_DATOS = new ArrayList<>();

public Data data(String hoja, int n) throws IOException {
    //ruta del excel
    XSSFWorkbook samplexlsx = new XSSFWorkbook("dataloader/excel.xlsx");
    //nombremos la hoja
    XSSFSheet sheet1 = samplexlsx.getSheet(hoja);
    //indicamos las posiciones del excel
    int rowCount = sheet1.getLastRowNum() + sheet1.getFirstRowNum();
    for (int fila = 0; fila < 3; fila++){
       String dato = "";

        for (int columna = 0; columna < 4; columna++){
            try {
               dato += sheet1.getRow(fila).getCell(columna).getNumericCellValue() + ";";
              //  System.out.print(sheet1.getRow(fila).getCell(columna).getNumericCellValue()+ ";");
            } catch (IllegalStateException ex) {
                dato += sheet1.getRow(fila).getCell(columna).getStringCellValue() + ";";
              //  System.out.print(sheet1.getRow(fila).getCell(columna).getStringCellValue()+ ";");
            }
        }
        //añadimos los datos en una lista
        listaDatos.add(dato);
    }
    //eliminamos la posición de Arraylist
    listaDatos.remove(0);
    //indicamos los datos que van a salir
    for ( String data : listaDatos){
  
        String [] datosPersonales = data.split(";");
        String url =  datosPersonales[0];
        String firstName =  datosPersonales[1];
        String lastName = datosPersonales[2];
        String id = datosPersonales[3];         
       
        Data p = new Data(url,firstName, lastName, Integer.parseInt(id));
        // ,Integer.parseInt(id));
        
      
        LISTA_DATOS.add(p);
        
    }
    
    return LISTA_DATOS.get(n);
   
   
}   

El objeto Data, esta indicando los valores que debe mostrar Gracias por poder ayudarme, un saludo! He modificado el recorrido del excel pero me da este error

int rowCount = sheet1.getLastRowNum()-sheet1.getFirstRowNum();
for (int i = 1; i < rowCount; i++) {
            String dato = "";
            Row row = sheet1.getRow(i);
            //int total = 0;
            //ArrayList<Integer> blank =new ArrayList<Integer>();
            //int type=-1;
            String s = null;
            for(int j = 0; j < row.getLastCellNum(); j++){
                try {
                    System.out.print(row.getCell(j).getStringCellValue()+"|| ");
                       dato += sheet1.getRow(i).getCell(j).getNumericCellValue() + ";";
                      // System.out.print(sheet1.getRow(i).getCell(j).getNumericCellValue()+ ";");
                    } catch (IllegalStateException ex) {
                        dato += sheet1.getRow(i).getCell(j).getStringCellValue() + ";";
                      //  System.out.print(sheet1.getRow(i).getCell(j).getStringCellValue()+ ";");
                    }
            }

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at excel.test.Ejemplo2.findRealRows(Ejemplo2.java:78) at excel.test.Ejemplo2.main(Ejemplo2.java:17)

1
  • Estoy diciendo añadiendo unos parámetros nuevos en el ciclo para recorrer toda la lista
    – mgarciaQA
    el 24 may. 2022 a las 7:55

1 respuesta 1

0

Solucionado! debemos añadir un try al principio, usando el código que he comentado antes. así sería:

public static Data findRealRows(String hoja, int n)  {
        //ruta del excel
                XSSFWorkbook samplexlsx;
                try {
                    samplexlsx = new XSSFWorkbook("dataloader/excel.xlsx");
                    //nombremos la hoja
                    XSSFSheet sheet1 = samplexlsx.getSheet(hoja);
            //int row_real = 0;
            // int rows = sheet1.getPhysicalNumberOfRows (); // Aquí hay errores en las estadísticas físicas del número de fila,
             int rowCount = sheet1.getLastRowNum()-sheet1.getFirstRowNum();
            //int size = flag.length;
            try {
         
         
            for (int i =1; i < rowCount; i++) {
                String dato = "";
                Row row = sheet1.getRow(i);
                //int total = 0;
                //ArrayList<Integer> blank =new ArrayList<Integer>();
                //int type=-1;
                String s = null;
                for(int j = 0; j < row.getLastCellNum(); j++){
                    try {
                        //System.out.print(row.getCell(j).getStringCellValue()+"|| ");
                           dato += row.getCell(j).getStringCellValue()+ ";";
                          // System.out.print(sheet1.getRow(i).getCell(j).getNumericCellValue()+ ";");
                        } catch (IllegalStateException ex) {
                            dato += row.getCell(j).getStringCellValue() + ";";
                          //  System.out.print(sheet1.getRow(i).getCell(j).getStringCellValue()+ ";");
                        }
                }
                // System.out.println (s + "Me");
                // System.out.println( "listad "+ listaDatos.add(dato));
                 listaDatos.add(dato);
        
         
            }
            
                
        //   System.out.println("new "+ LISTA_DATOS.get(1).getNombre());
            // return LISTA_DATOS.get(1);
            }
            
            catch (NullPointerException e) {
                // lanzar una nueva BusinessException ("Excepción de formato de Excel, compruebe si faltan datos en formato Excel, filas de datos no válidas");
            }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                
                  // listaDatos.remove(0);
                 for ( String data : listaDatos){
                      
                        String [] datosPersonales = data.split(";");
                        String url =  datosPersonales[0];
                        String firstName =  datosPersonales[1];
                        String lastName = datosPersonales[2];
                        String id = datosPersonales[3];         
                       
                        Data p = new Data(url,firstName, lastName, Integer.parseInt(id));
                        // ,Integer.parseInt(id));
                     //   System.out.println("new  "+data.toString());
                      
                        LISTA_DATOS.add(p);
                        
                    }
                 //System.out.println(LISTA_DATOS.get(1).getNombre());
        return LISTA_DATOS.get(n);
          
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.