阅读美国邮政编码从Excel使用Apache poi

我使用下面的代码从我的Excel文件中读取具有如下值的邮政编码:

06785

excel文件单元格格式化为特殊的>> zipcode

File src = new File("C:\\Users\myxl.xlsx"); FileInputStream fis = new FileInputStream(src); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sh1 = wb.getSheetAt(0); System.out.println(sh1.getRow(1).getCell(19).getRichStringCellValue()); //Output = Can not get a text value form a numeric cell wb.close(); fis.close(); 

我试过了以下几点:

 System.out.println(sh1.getRow(1).getCell(19).getStringCellValue()); //Output = Can not get a text value form a numeric cell System.out.println(sh1.getRow(1).getCell(19).toString()); //Output = 6785.0 System.out.println(sh1.getRow(1).getCell(19).getNumericCellValue()); //Output = 6785.0 System.out.println(sh1.getRow(1).getCell(19).getRawValue()); //Output = 6785 

我不能得到完全像它出现在Excel中的值,即06785 ,它始终打印没有0或0。

任何人都可以帮助,因为我将得到一个邮政编码的输出,因为它确切地出现在Excel – 06785

这似乎现在解决了这个问题(使用DecimalFormat)。

如果其他人有更好的答案,请在这里提供您的宝贵意见。

非常感谢迄今为止所有的投入。

 String myint = new java.text.DecimalFormat("00000").format(sh1.getRow(1).getCell(19).getNumericCellValue()); //OR DecimalFormat df= new DecimalFormat("00000"); String formatted = df.format(sh1.getRow(1).getCell(19).getNumericCellValue()); System.out.println(myint); System.out.println("******"); System.out.println(formatted); 

首先,我们需要从下面的单元格中获取string的值。

 cell.setCellType(Cell.CELL_TYPE_STRING); cellValueAsString = zeroPaddingToZipCode(cell.getStringCellValue();); 

那么我们需要有类似的function,如下所示填充或非填充邮政编码。

 private String zeroPaddingToZipCode(String cellValueAsString) { if(null != cellValueAsString){ if(!cellValueAsString.contains("-")){ if(cellValueAsString.length() == 4 ){ cellValueAsString = "0"+cellValueAsString; } } else { String[] zipCodes = cellValueAsString.split("-"); if(zipCodes.length == 2 ) { if(zipCodes[0].length() == 4 || zipCodes[0].length() == 2 ) { cellValueAsString = "0"+zipCodes[0]; } else { cellValueAsString = zipCodes[0]; } cellValueAsString += "-"; if(zipCodes[1].length() == 4 || zipCodes[1].length() == 2 ) { cellValueAsString += "0"+zipCodes[1]; } else { cellValueAsString += zipCodes[1]; } } } } return cellValueAsString; } 

检查它是否工作