2017-04-22 70 views
1

我读包含使用Apache POI一些数值的Excel文件,我希望当我输入cell.setCellType(Cell.CELL_TYPE_STRING);这表明像这样(http://imgur.com/a/hZvUl),以便然后转换为字符串设置电池类型错误

,我得到一个NullPointerException

任何人都可以帮我吗?

public void CreateDir() throws IOException { 
    try { 
     if (getStartAvailablility() == false) { 
      JOptionPane.showMessageDialog(null, "Please Choose Where To Save The Files First!!"); 
     } else { 
      JOptionPane.showMessageDialog(null, "Working On It Please Wait.."); 
      btnStart.setEnabled(false); 

      FileInputStream fis = new FileInputStream(getChooseFilepath()); 
      XSSFWorkbook wb = new XSSFWorkbook(fis); 
      XSSFSheet sheet = wb.getSheetAt(0); 
      for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { 

       XSSFRow row = sheet.getRow(i); 
       XSSFCell cell = row.getCell(2); 

       cell.setCellType(Cell.CELL_TYPE_STRING); 
       try { 
        if (cell != null) { 
         File dir = new File(getWorkSpacePath() + "\\" + cell); 
         // if the directory does not exist, create it 
         //System.out.println(Files.list(Paths.get(getWorkSpacePath()+dir.getName())).count()); 

         if (!dir.exists()) { 
          try { 
           dir.mkdir(); 

          } catch (SecurityException se) { 
           se.printStackTrace(); 
          } 
         } 

`你正在使用过时的东西

+0

....为什么? –

+0

对不起,我没有undertsant – Qubayl

+0

你确定你的单元格不是null? – strash

回答

0
public void CreateDir() throws IOException { 
    //.... 

    XSSFCell cell = row.getCell(2); 
    cell.setCellValue(getCellValue(cell)); 
    //Value of cell is converted to String. 
    //Setting a cell to a string value sets the cell type to a String. 

    //.... 
} 

//helper method that grabs cell value regardless of type, and converts to String 
public static String getCellValue(Cell cell){ 
    String a = ""; 
    int b; 
    double c; 
    if(cell != null){ 
     int type = cell.getCellType(); 
     switch (type) { 
      case Cell.CELL_TYPE_NUMERIC: 
       c = cell.getNumericCellValue(); 
       if(c%1 == 0){ 
        b = (int) c; 
        a = b + ""; 
       }else{ 
        a = c + ""; 
       } 
       break; 
      case Cell.CELL_TYPE_STRING: 
       a = cell.getStringCellValue(); 
       break; 
      case Cell.CELL_TYPE_FORMULA: 
       a = cell.getCellFormula() + ""; 
       break; 
      case Cell.CELL_TYPE_BLANK: 
       a = ""; 
       break; 
      case Cell.CELL_TYPE_BOOLEAN: 
       a = cell.getBooleanCellValue() + ""; 
       break; 
      default: 
       break; 
     } 
    } 
    return a; 
}