简体   繁体   中英

How to extract only the integer value instead of the Double value when reading data from Excel using Java

I need a code which should get data from Excel as int values instead of String values.

It is displaying the value 2.0 which was originally saved in sheet as 2`

Try 1:

HSSFCell number = sheet.getRow(1).getCell(26);
Integer result =Integer.valueOf(number);                
System.out.println(result);

Try 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)

Code:

System.out.println(+sheet.getRow(1).getCell(26));

Output: 2.0

Expected output : 2

I recommend the following way, which does not try to cast an HSSFCell to an 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;

Once you read the Double values from the excel instead of displaying the values as 2.0 , to print it as 2 you can use the DecimalFormat Class methods and you can use the following solution:

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

Incase your usecase is to print the String format you can add String.valueOf() and you can use the following solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM