2017-08-21 39 views
0

在excel中有一列Value1,其中包含價格..例如$ 2789.98,$ 32321.45。我想獲得這些值,並需要添加,例如:2789.98 + 32321.45。從Excel獲取價格並需要使用POI計算值

public void testData() throws IOException { 
    Object[] calc = this.readExcelByColName("Calculations"); 
    for (int i = 1; i < calc.length; i++) { 
     String string = (String) calc[i-1]; 
     string = string.replaceAll("\\s", ""); 
     String[] parts = string.split("(\\=)"); 
     String[] parts1 = parts[0].split("(\\+)"); 
     DataFormatter df = new DataFormatter(); 
     if (parts.length == 2 && parts1.length > 1) { 
      String value1 = df.formatCellValue(this.sheet.getRow(i).getCell(2)); 
      String value2 = df.formatCellValue(this.sheet.getRow(i).getCell(3)); 
      String value3 = df.formatCellValue(this.sheet.getRow(i).getCell(4)); 
      float result= (Float.parseFloat(value1.toString().substring(1).replaceAll(",", "")) + Float.parseFloat(value2.toString().substring(1).replaceAll(",", ""))); 
      if (result == Float.parseFloat(value3.toString().substring(1).replaceAll(",", ""))) {     
       this.sheet.getRow(i).getCell(5).setCellValue("Pass"); 
      } else { 
       this.sheet.getRow(i).getCell(5).setCellValue("Fail"); 
      } 
+0

我可以能夠得到的價格與$符號和刪除使用substring,然後轉換爲整數,但在if(result == Integer.parseInt(value3)){condition,它不會將這兩個值都添加到結果變量中。 –

+0

運行int result = Integer.parseInt(value1.toString()。substring(1))+ Integer.parseInt(value2.toString()。substring(1))測試用例正在失敗。 –

+0

它沒有返回任何東西,TC出錯了。看起來轉換有問題。我已檢查轉換爲雙倍,但沒有工作。 –

回答

0

好像你正在使用括號「()」在錯誤的地方

嘗試使用下面的代碼,只需複製並粘貼

float result= Float.parseFloat(value1.toString().substring(1).replaceAll(",", "")) + Float.parseFloat(value2.toString().substring(1).replaceAll(",", "")); 
+0

是的......現在正在工作..謝謝了很多 –

+0

@KiranP - 你能接受答案嗎?謝謝 – Kapil

+0

當然..我還有一個問題。 this.sheet.getRow(ⅰ).getCell(5).setCellValue( 「通」);我無法將單元格值設置爲我的Excel。可能是什麼問題。 –