2017-08-28 62 views
0
FileInputStream file=new FileInputStream ("C:\\Users\\sagar.lankegowda\\Desktop\\My workspace\\adt bundle\\adt-bundle-windows-x86_64-20140702\\eclipse\\Excel\\UserCreditanls.xls"); 
Workbook wb=WorkbookFactory.create(file); 
Sheet st=wb.getSheet("Sheet1"); 
Row r= st.getRow(0); 
Cell c=r.getCell(1); 
String str=""; 

if(c.equals(str)) 
{ 
    System.out.println(c.getStringCellValue()); 
} 
//System.out.println(str); 
else 
{ 
    System.out.println(c.getNumericCellValue()); 
} 
System.out.println(str); 

在一個程序中如何我讀從Excel字符串和數字雖然運行此代碼我得到一個異常:在java中硒

Exception in thread "main" java.lang.IllegalStateException: Cannot get a NUMERIC value from a STRING cell 
+0

一種方式是,你可以從數字格式的單元格在Excel工作表中的文本。我想這可以解決你的問題 – Nidhi257

回答

2

你可以做這裏只是格式細胞根據需要鍵入。 我張貼它下面的代碼:

private static String formatCell(Cell cell) 
{ 
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.getDefault()); 
    DecimalFormat df = (DecimalFormat)nf; 
    df.setRoundingMode(RoundingMode.CEILING); 
    df.setGroupingUsed(false); 
    df.setMaximumFractionDigits(2); 
    if (cell == null) { 
     return ""; 
    } 
    switch(cell.getCellType()) { 
     case Cell.CELL_TYPE_BLANK: 
      return ""; 
     case Cell.CELL_TYPE_BOOLEAN: 
      return Boolean.toString(cell.getBooleanCellValue()); 
     case Cell.CELL_TYPE_ERROR: 
      return "*error*"; 
     case Cell.CELL_TYPE_NUMERIC: 
      return df.format(cell.getNumericCellValue()); 
     case Cell.CELL_TYPE_STRING: 
      return cell.getStringCellValue(); 
     case Cell.CELL_TYPE_FORMULA: 
      return df.format(cell.getNumericCellValue()); 
     default: 
      return "<unknown value>"; 
    } 
} 

,並呼籲:

formatCell(row.getCell(0))