javaexcelseleniumapache-poir.java-file

Unable to accept two dimensional String Array returned from a method


First of All :-) , I am not that proficient in java.

So in below code I am trying to print a two dimensional string returned from method. But unable to do it. Getting type mismatch error. can any one help.

public class ExcelUtilAdvanced {

    public String[][] getDatafromExcel(){
        
        int rowCount = sheet.getPhysicalNumberOfRows();
        int colCount = sheet.getRow(0).getPhysicalNumberOfCells();
        String[][] data = new String[rowCount-1][colCount];
        Row row;
        Cell cell;
        for(int i=1;i<rowCount;i++) {
            row = sheet.getRow(i);
            for(int j=0;j<colCount;j++) {
                cell = row.getCell(j);
                data[i-1][j] = format.formatCellValue(cell);
            }
        }
        System.out.println(data);
    return data;
        
    }
    public static void main(String[] args) {
        
        int rowCount = 2;
        int colCount = 7;
        
        ExcelUtilAdvanced eua = new ExcelUtilAdvanced("fileName.xlsx", "sheetName");
        String[][] data = new String[rowCount][colCount];
        
        for(int i=1;i<rowCount;i++) {
            for(int j=0;j<colCount;j++) {
                data[i-1][j]= eua.getDatafromExcel(); //Type Type mismatch: cannot convert from String[][] to String
            }
            
        }
        
    }

Solution

  • You are passing a String[][] object into a String variable. I think you can declare and initialize directly the String[][] object passing the result returned by that method.

    public static void main(String[] args) {
    
        int rowCount = 2;
        int colCount = 7;
    
        ExcelUtilAdvanced eua = new ExcelUtilAdvanced("fileName.xlsx", "sheetName");
        String[][] data = eua.getDatafromExcel();
    }
    

    Edit: Also, you have to modify the rest of your code, so you'll able to handle rowCount and colCount variables (maybe you can put them in first method as input parameters), cause you aren't using those in String[][] declarations.

    Like:

    String[][] data = eua.getDatafromExcel(rowCount, colCount);
    

    And you have to put System.out.println at the end of each loops, in order to print your String[][] while you assign values. You can't print just your data variable.

    General example:

    for(int i = 1; i < rowCount; i++) {
        for(int j = 0; j < colCount; j++) {
            System.out.print(data[i-1][j] + " ");
        }
        System.out.println();
    }