簡體   English   中英

如何將Excel中單元格的字符串值轉換為數值以進行各種計算?

[英]How to convert string value of a cell in excel to numeric to do various calculations?

Sheet sheet = w.getSheet(0);
data = new String[sheet.getColumns()][sheet.getRows()];
data1 = new String[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(data[j][i]);
        // System.out.println(cell.getContents());
    } System.out.println();
}

我需要找到數組data[j][i]總和,但是由於它是一個字符串而無法找到它。

JXL有一個稱為NumberCell的類, NumberCellgetValue()方法返回一個double。

請參閱此處的文檔。

因此,如果將數據數組更改為兩倍,則可以替換:

Cell cell = sheet.getCell(j, i);
data[j][i] = cell.getContents();

與:

NumberCell cell = (NumberCell)sheet.getCell(j, i);
data[j][i] = cell.getValue();

然后您可以對此進行計算。

當然,如果您知道該值是整數,則可以相應地對其進行強制轉換。

請注意,最好先檢查類型,例如:

if (sheet.getCell(j, i).getType() == CellType.NUMBER)

並在轉換未知/未經檢查的輸入時將其包裝為try / catch。

暫無
暫無

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

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