使用Apache POI将单元格转换为整数的解决方法如下所示:
CellType
类判断单元格的数据类型。如果单元格的数据类型为数字类型(NUMERIC
),则执行下一步;否则,忽略该单元格。if (cell.getCellType() == CellType.NUMERIC) {
// 执行转换操作
}
getNumericCellValue()
方法获取单元格的数值,并将其转换为整数类型。double numericValue = cell.getNumericCellValue();
int intValue = (int) numericValue;
以下是一个完整的示例代码:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("path/to/your/excel/file.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.NUMERIC) {
double numericValue = cell.getNumericCellValue();
int intValue = (int) numericValue;
System.out.println("Integer value: " + intValue);
}
}
}
workbook.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意,以上示例代码是基于Apache POI 4.0.0版本编写的。如果你使用的是其他版本,请根据实际情况进行调整。