2012-03-26 9 views
5

Quiero leer los valores de hoja de Excel y almacenar esos valores en una matriz en Java.¿Cómo se leen los valores del archivo excel y se almacenan en Array?

Tengo el código listo para leer la hoja de Excel, pero no puedo personalizarlo para almacenar esos valores en Array.

Aquí está mi código para leer una hoja de Excel:

package com.core.testscripts; 

import java.io.File; 
import java.io.IOException; 

import jxl.Cell; 
import jxl.Sheet; 
import jxl.Workbook; 
import jxl.read.biff.BiffException; 

public class NewExcel 
{ 

    private String inputFile; 

    public void setInputFile(String inputFile) 
    { 
     this.inputFile = inputFile; 
    } 

    public void read() throws IOException 
    { 
     File inputWorkbook = new File(inputFile); 
     Workbook w; 
     try 
     { 
      w = Workbook.getWorkbook(inputWorkbook); 
      // Get the first sheet 
      Sheet sheet = w.getSheet(0); 
      // Loop over first 10 column and lines 

      for (int j = 0; j < sheet.getColumns(); j++) 
      { 
       for (int i = 0; i < sheet.getRows(); i++) 
       { 
        Cell cell = sheet.getCell(j, i); 
        System.out.println(cell.getContents()); 
       } 
      } 
     } 
     catch (BiffException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) throws IOException 
    { 
     NewExcel test = new NewExcel(); 
     test.setInputFile("D:/hellohowareyou.xls"); 
     test.read(); 
    } 

} 
+1

¿Cómo quiere leer? Todas las celdas de todas las filas en una sola matriz? ¿O todas las celdas por fila en una matriz bidimensional? – Nik

Respuesta

0

Si realmente quieres una matriz, que van a tener que saber cuántos elementos que desee en la matriz cuando se puede asignar almacenamiento para la misma. Puede hacerlo en tiempo de ejecución, no es necesario conocerlo en tiempo de compilación, pero debe hacerlo antes de poder usar la matriz.

En algún lugar en una sección de declaraciones:

String[] dataArray = null; 

y luego en algún lugar del código

dataArray = new String[numberOfElements]; 

Se puede hacer una de dos (o más) matriz bidimensional en el mismo principio. Después de eso, puede asignar una cadena a cualquier elemento de la matriz en un índice menor que numberOfElements.

+0

Soy un QA y quiero utilizar este código para mi propósito de prueba. Tengo una hoja de Excel que tiene 5 valores. Y tengo el comando Selenium de la búsqueda de Google en otra clase: selenium.type ("css = # gbqfq", "Hola"); ahora en este comando quiero usar esos valores de la hoja de Excel y ejecutar este comando usando esos valores en lugar de "Hola". –

2
import java.io.File; 
import java.io.IOException; 

import jxl.Cell; 
import jxl.Sheet; 
import jxl.Workbook; 
import jxl.read.biff.BiffException; 

public class NewExcel 
{ 

    private String inputFile; 
    String[][] data = null; 
    public void setInputFile(String inputFile) 
    { 
     this.inputFile = inputFile; 
    } 

    public String[][] read() throws IOException 
    { 
     File inputWorkbook = new File(inputFile); 
     Workbook w; 

     try 
     { 
      w = Workbook.getWorkbook(inputWorkbook); 
      // Get the first sheet 


      Sheet sheet = w.getSheet(0); 
      data = new String[sheet.getColumns()][sheet.getRows()]; 
      // Loop over first 10 column and lines 
     //  System.out.println(sheet.getColumns() + " " +sheet.getRows()); 
      for (int j = 0; j <sheet.getColumns(); j++) 
      { 
       for (int i = 0; i < sheet.getRows(); i++) 
       { 
        Cell cell = sheet.getCell(j, i); 
        data[j][i] = cell.getContents(); 
        // System.out.println(cell.getContents()); 
       } 
      } 

     /* for (int j = 0; j < data.length; j++) 
      { 
       for (int i = 0; i <data[j].length; i++) 
       { 

        System.out.println(data[j][i]); 
       } 
      } */ 

     } 
     catch (BiffException e) 
     { 
      e.printStackTrace(); 
     } 
    return data; 
    } 


} 
0
package Utilities; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 

import org.apache.poi.ss.usermodel.Cell; 
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; 

public class ExcellReading { 

    // public Workbook workbook= null; 
    // public Sheet firstSheet= null; 

    public String INPUT_XLS = "/ExcelManipulation/TestExecution.xlsx"; 

    public ExcellReading() { 
    } 

    public ExcellReading(String filepath) { 
     INPUT_XLS = filepath; 
    } 

    public Map<Integer, List<String>> ReadExcel() throws IOException { 

     FileInputStream inputStream = new FileInputStream(new File("TestExecution.xlsx")); 

     Map<Integer, List<String>> data = new HashMap<Integer, List<String>>(); 

     Workbook workbook = new XSSFWorkbook(inputStream); 

     Sheet firstSheet = workbook.getSheetAt(5); 

     Iterator<Row> iterator = firstSheet.iterator(); 

     // Test test=new Test(); 
     int rowCnt = 0; 

     while (iterator.hasNext()) { 
      Row nextRow = iterator.next(); 

      Iterator<Cell> cellIterator = nextRow.cellIterator(); 
      List<String> obj = new ArrayList<String>(); 
      while (cellIterator.hasNext()) { 
       Cell cell = cellIterator.next(); 

       String cellobj = cell.getStringCellValue(); 

       if ("".equals(cell.getStringCellValue())) { 
        obj.add("Missing"); 

       } else if (cellobj.equals(null)) { 
        obj.add(""); 

       } else { 
        obj.add(cell.getStringCellValue()); 
       } 

      } 

      data.put(rowCnt, obj); 
      rowCnt++; 

     } 
     return data; 
    } 

} 
Cuestiones relacionadas