Search code examples
javaapache-poitype-mismatchtypecasting-operator

Type casting error Java, Apache POI


I am a beginner programmer in Java and this is the code that I have written so far:

public class Fastclass {
  public static void main (String[] args) throws Exception{

    String[] data;
    data = excelRead();
    for (int i = 1; i < data.length; i++){

        findcontact(data[i]);

    }
  }

  public static String[] excelRead() throws Exception{
    File excel = new File ("C:\\Users\\user\\Desktop\\Folder\\subfolder\\Data.xlsx");
    FileInputStream fis = new FileInputStream(excel);
    HSSFWorkbook wb = new HSSFWorkbook (fis);
    HSSFSheet ws = wb.getSheet("Sheet1");

    int rowNum = ws.getLastRowNum() + 1;
    String[] data = new String [rowNum];

    for (int i=1; i<rowNum; i++){

        HSSFRow row = ws.getRow(i);
        HSSFCell cell = row.getCell(i);
        String value = cellToString(cell);
        data[i] = value;        

    }

    **return data[i];**
  }


  public static String cellToString (HSSFCell cell) {
    int type;
    Object result;
    type = cell.getCellType();
    switch(type){
    case 0: // numeric value in excel
        result = cell.getNumericCellValue();
        break;
    case 1: //String value in excel
        result = cell.getStringCellValue();
        break;
        default:
            throw new RuntimeException("There are no support for this type of cell");
    }

    return result.toString();
  }

}

Function excelRead is used to read an excel file and function cellToString is used to convert different data types cells in excel.

The findcontact function that is being called from the main class is the actual logic that I need to implement. However that is not important from the perspective of this question.

I get an error on the return statement in the excel read function and the error is cannot convert string to string[] (string array). Any help appreciated. Thank you so much.


Solution

  • Your function excelRead should return a String[] (because you're assigning the result to data, a String[]). That is

    return data[i]; // <-- a String
    

    should be

    return data; // <-- a String[]