Was*_*ani 2 java apache excel apache-poi
我正在尝试在 java(使用 Apache POI API)中读取 .xlsx 文件,其单元格包含具有前导零的值。例如 0590040100000124
但在输出中我得到了这样的东西
6247241.0 <-> 5.90040100000124E14 <-> 0.0 <-> 5.90020100000125E14 <-> 这是我的代码
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
try{
Workbook workbook = new XSSFWorkbook(new FileInputStream("C://dedup//dedup.xlsx"));
String sheetName= workbook.getSheetName(0);
System.out.println("Sheet Name:"+sheetName);
double cellValues[] = new double[1000];
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
int cellIndex=0;
for (Row row : sheet) {
for (Cell cell : row) {
//if(cell.toString()!=null){
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cellValues[cellIndex]=cell.getNumericCellValue();
cellIndex++;
//}
}
}
for(int k=0;k<cellValues.length;k++)
System.out.print(cellValues[k]+" <-> "+"\t");
}
}catch(Exception e){
System.out.println("JKB Exception Message:"+e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)
您的问题是您将值作为双精度值获取(Excel 中的数字除了少数边缘情况外,存储为浮点数)。从 Java 打印的浮点数没有前导零,使用科学格式等
假设您真正想要的是“给我一个看起来像 Excel 为该单元格显示的字符串”,那么您不想打印原始双精度值。相反,您需要使用DataFormatter 类,该类提供读取应用于单元格的 Excel 格式规则的方法,然后在 Java 中重新创建(尽其所能)这些规则
你的代码应该是:
DataFormatter fmt = new DataFormatter();
String numberAsInExcel = fmt.formatCellValue(cell);
Run Code Online (Sandbox Code Playgroud)
这将根据 Excel 中应用的格式规则格式化数字,因此应该按照您的预期返回它,前导零,非科学格式等
| 归档时间: |
|
| 查看次数: |
3299 次 |
| 最近记录: |