![](/img/trans.png)
[英]When reading cell data from excel in java it returns decimal value
[英]How to extract only the integer value instead of the Double value when reading data from Excel using Java
我需要一個代碼,該代碼應該從Excel以int值而不是String值獲取數據。
它顯示的是值2.0
,該值最初保存在工作表中為2`。
嘗試1:
HSSFCell number = sheet.getRow(1).getCell(26);
Integer result =Integer.valueOf(number);
System.out.println(result);
嘗試2:
int L = Integer.parseInt(getRow(1).getCell(26));
Error:The method parseInt(String) in the type Integer is not applicable for the arguments (Cell)
碼:
System.out.println(+sheet.getRow(1).getCell(26));
輸出:2.0
預期產量:2
我建議采用以下方式,不要嘗試將HSSFCell
轉換為Integer
/ int
:
// get the cell as object (this is NOT a number, instead, it contains one)
HSSFCell numberCell = sheet.getRow(1).getCell(26);
// get the cell value as double (there is no direct integer version)
double cellValue = numberCell.getNumericCellValue();
// cast the value to an int
int number = (int) cellValue;
一旦從excel讀取Double值而不是將其顯示為2.0即可將其打印為2 ,則可以使用DecimalFormat 類方法,並且可以使用以下解決方案:
HSSFCell number = sheet.getRow(1).getCell(26);
Double result =Double.valueOf(number);
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
System.out.println(format.format(result));
如果您的用例是打印String格式,則可以添加String.valueOf()
並且可以使用以下解決方案:
HSSFCell number = sheet.getRow(1).getCell(26);
Double result =Double.valueOf(number);
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
System.out.println(String.valueOf(format.format(result)));
你可以試試
int L = Integer.parseInt(getRow(1).getCell(26).getStringCellValue());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.