在Java中使用Apache POI从数字单元格读取整数 [英] Read integer from numeric cell using Apache POI in java
问题描述
我有一个使用apache poi读取xls表的应用程序.当单元格具有数值时,我通过row.getCell(i).getNumericValue()进行读取.但是它返回浮点数.像如果单元格值为1,则返回1.0.我可以将其转换为int吗?任何帮助,将不胜感激.我尝试了Integer.parseInt(value)-,但是它抛出NumberFormat异常.感谢您的帮助.以下是伪代码:
I have an application which reads xls sheet using apache poi. When the cell has numeric value, i read it by row.getCell(i).getNumericValue(). But it returns floating point digit. like if the cell value is 1, it returns 1.0. Can i convert it to int ? Any helpwould be appreciated. I tried Integer.parseInt(value)- but it throws NumberFormat exception.Any help is appreciated.Here is the pseudo code:
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String value= String.valueOf(cell.getNumericCellValue());
int intVal = Integer.parseInt(value)-->>throws Exception
推荐答案
您可以使用简单的步骤将int值读取为字符串apache poi
You can read int value as string apache poi using simple steps
首先使用以下方法计算工作表中的行
First count rows in sheets using below method
private int getRowCount(Sheet currentSheet) {
int rowCount = 0;
Iterator<Row> rowIterator = currentSheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
if(row == null || row.getCell(0) == null || row.getCell(0).getStringCellValue().trim().equals("") || row.getCell(0).toString().trim().equals("")
|| row.getCell(0).getCellType()==Cell.CELL_TYPE_BLANK){
break;
}
else
rowCount=rowCount + 1;
}
return rowCount;
}
然后在您的方法中使用以下代码
Then use below code in your method
Workbook workbook = WorkbookFactory.create(new File("c:/test.xls");
Sheet marksSheet = (Sheet) workbook.getSheet("Sheet1");
int zoneLastCount = 0;
if(marksSheet !=null ) {
zoneLastCount = getRowCount(marksSheet);
}
int zone = zoneLastCount-1;
int column=1
for(int i = 0; i < zone; i++) {
Row currentrow = marksSheet.getRow(i);
double year = Double.parseDouble(currentrow.getCell(columnno).toString());
int year1 = (int)year;
String str = String.valueOf(year1);
}
这篇关于在Java中使用Apache POI从数字单元格读取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!