簡體   English   中英

為什么我們不能通過使用cell.toString()而不是創建新的cellToString(cell)方法將excel單元格值直接轉換為字符串

[英]Why we can't directly convert the excel cell value to string by using cell.toString() instead of creating a new cellToString(cell) method

我已經使用Apache POI創建了一個Excel閱讀器。 我能夠得到單元格的值:

cell=sh.getRow(row).getCell(col);

此后,我想將單元格對象轉換為字符串,因為我的Excel工作表單元格可以是任何類型,因此我將其轉換為通用字符串值。 因此,我可以通過編寫以下代碼來做到這一點:

data[row][col]=cell.toString(); 

但是,我看到了通常遵循的做法,即創建一個新的cellToString方法,如下所示:

public String cellToString(HSSFCell cell){
int type;
    Object result;
    type=cell.getCellType();

    switch(type){
        case 0:
            result=cell.getNumericCellValue();
            break;
        case 1:
            result=cell.getStringCellValue();
            break;
            default:
                throw new RuntimeException("There is no support of this type of cell");
    }
            return result.toString();
}

然后像上面那樣調用上面的函數:

data[row][col]=cellToString(cell);

有人可以告訴我為什么我們不直接遵循第一種方法,因為它同樣有效。

我敢打賭,在大多數情況下,您最好使用包裝紙,例如:

  • 您想要確保僅處理某些類型的單元格,並拋出所有其他類型,如上述cellToString()的實現者顯然想做的那樣

  • 您不需要區分丟失的單元格和空的單元格,也不希望您的代碼getCell()在檢查getCell()的返回值getCell()null

  • 您對單元格的默認格式不滿意

..或其他任何情況,當您不滿意要咀嚼的任何琴弦時。 您的里程肯定會有所不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM