2015-09-11 32 views
-1

我在Java初學者程序員,這是我迄今所編寫的代碼:使用類型轉換錯誤的Java,Apache的POI

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(); 
    } 

} 

功能excelRead用於讀取Excel文件和功能cellToString在Excel中轉​​換不同的數據類型單元格。

從主類調用的findcontact函數是我需要實現的實際邏輯。但從這個問題的角度來看這並不重要。

我在excel讀取函數的return語句中出錯,錯誤是無法將字符串轉換爲string [](string array)。任何幫助讚賞。非常感謝。

回答

2

您的功能excelRead應返回String[](因爲您將結果分配給dataString[])。也就是說

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

應該

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

謝謝埃利奧特和你們其他人 – user3777207

1

這是一個有點難以閱讀的代碼(可能格式化),但如果返回數據[I]是你的返回語句,那麼你只是返回一個字符串數組中的一個元素。

只是使用「返回數據」;而不是

1

你的方法簽名:

public static String[] excelRead() throws Exception 

說要返回一個String數組,但你回來從你的數組中的元素(字符串)。

也許你想返回整個數組:

return data; 

或更改方法簽名:

public static String excelRead() throws Exception 

,並返回一個字符串數組元素像你想幹什麼?

0

根據以下方法簽名,你應該返回字符串數組

public static String[] excelRead() throws Exception 

這裏因爲你是返回一個字符串

**return data[i];** 

要麼改變你的方法簽名,以便返回類型爲字符串或返回字符串[]