2016-12-18 2 views
0

Я пытаюсь добавить лист с Apache POI, однако я получаю исключение Null Pointer, когда пытаюсь сохранить excel. Не уверен, почему это происходит, однако обновление данных до Превосходство бывает совершенным.Невозможно добавить лист с помощью Apache POI ss user model

произошло исключение: org.apache.poi.POIXMLException: java.lang.NullPointerException

public XL_ReadWrite(String path) throws Exception{ 
    this.path = path; 
    try{ 
     fin = new FileInputStream(path); 
     workbook = WorkbookFactory.create(fin); 
     sheet = workbook.getSheetAt(0); 
     fin.close(); 
    } catch(FileNotFoundException e){ 
     throw new Exception("Exception occurred while finding the file : " + path + " while XLS initialize .Exception details : "+e.getMessage()); 
    } catch(IOException e){ 
     throw new Exception("I/O interrupted exception occurred while XLS initialize .Exception details : " + e.getMessage()); 
    } catch(Exception e){ 
     throw new Exception("Exception occurred while XLS initialize .Exception details : "+ e.getMessage()); 
    } 
} 

public void addSheet(String sheetName) throws Exception{ 
     File file = new File(path); 
     String fileExtn = Globals.GC_EMPTY; 
     workbook = null; 
     if (file.exists()) { 
      try { 
       fileExtn = FilenameUtils.getExtension(file.getAbsolutePath()); 
       if(fileExtn.equals("xlsx")){ 
        workbook = (XSSFWorkbook) WorkbookFactory.create(file); 
       }else if(fileExtn.equals("xls")){ 
        workbook = (HSSFWorkbook) WorkbookFactory.create(file); 
       } 
       sheet = workbook.createSheet(sheetName); 
      }catch (InvalidFormatException e) { 
       throw new Exception("InvalidFormatException occurred while adding sheet : " + sheetName + ". Exception details : "+e.getMessage());  
      }catch(IOException e){ 
       throw new Exception("IOException occurred while adding sheet : " + sheetName + ". Exception details : "+e.getMessage()); 
      } 
     } 
     else{ 
      throw new FileNotFoundException("Error : " + path + " not found"); 
     } 
    } 

public void saveXL() throws Exception{  
     try{ 
      fout = new FileOutputStream(path); 
      this.workbook.write(this.fout); 
      this.fout.close(); 
     }catch(Exception e){ 
      throw new Exception("Exception occurred while saving excel. Exception details :" +e.getMessage()); 
     } 
    } 

ответ

1

Выпуск фиксированного

if(fileExtn.equals("xlsx")){ 
        workbook = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(path)); 
       }else if(fileExtn.equals("xls")){ 
        workbook = (HSSFWorkbook) WorkbookFactory.create(new FileInputStream(path)); 
       } 
+0

Почему вы думаете, что это нужно вообще? Почему бы просто не использовать WorkbookFactory и не автообнаружение? – Gagravarr

Смежные вопросы