在写入Apache POI工作簿时获取java.lang.NullPointerException

时间:2020-03-23 12:31:45

标签: java excel apache-poi

在写入文件输出流的 POI工作簿时,我得到了java.lang.NullPointerException

下面是代码:

public void generate(String outFileName) throws Exception
  {
OutputStream fileOut = null;
File file = new File(outFileName);
if(!file.exists()) {
   file.createNewFile();
}
fileOut = new FileOutputStream(file);

String templateFileNameWithDir = "doc/IntradoTvwGenerateTemplate.xls";

Workbook inWorkbook = getWorkbook(templateFileNameWithDir);
Workbook outWorkbook = copyWorkbook(outFileName, inWorkbook);
int currentRow = 0;
currentRow = addRowsNew(fileOut, outWorkbook, inWorkbook.getSheetAt(0));

      outWorkbook.write(fileOut);
      outWorkbook.close();
      inWorkbook.close();
      fileOut.flush();
      fileOut.close();
}

public Workbook getWorkbook(String templateFileNameWithDir) throws Exception
  {
    InputStream ios = null;
    Workbook inWorkBook = null;
    try{
        File inputFile = new File(templateFileNameWithDir);
        ios = new FileInputStream(inputFile);
        inWorkBook = WorkbookFactory.create(ios);
    }
    finally {
        ios.close();
    }
    return inWorkBook;
  }

public Workbook copyWorkbook(String outFileName, Workbook inWorkbook) throws Exception
  {
    Workbook outWorkbook = inWorkbook;
    return outWorkbook;
  }

在这行 generate()方法中,我得到了NullPointer,-

outWorkbook.write(fileOut);

异常日志如下:

java.lang.NullPointerException
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode$FilteringIterator.<init>(FilteringDirectoryNode.java:193)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode$FilteringIterator.<init>(FilteringDirectoryNode.java:188)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode.getEntries(FilteringDirectoryNode.java:101)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode.iterator(FilteringDirectoryNode.java:105)
    at org.apache.poi.poifs.filesystem.EntryUtils.copyNodes(EntryUtils.java:74)
    at org.apache.poi.poifs.filesystem.EntryUtils.copyNodes(EntryUtils.java:90)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1465)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1439)
    at com.sprint.neo.e911.util.SpreadSheetIteratorHelper.generate(SpreadSheetIteratorHelper.java:495)
at com.sprint.neo.e911.util.tvw.TVWSpreadSheetGenerator.generateIntradoTVWSpreadSheet(TVWSpreadSheetGenerator.java:96)

请帮助我解决此错误。预先感谢。

编辑:添加 addRowsNew()方法

public int addRowsNew(OutputStream out, Workbook wb, Sheet sourceSheet){

int currentRow=0;
Sheet outSheet = wb.getSheetAt(0);
CellStyle cellStyle = null;
Row row = sourceSheet.getRow(rowStart);
cellStyle = row.getCell(i).getCellStyle();

Row rowOut = outSheet.createRow((short)currentRow);
Cell cell = rowOut.createCell(2);
cell.setCellStyle(cellStyle);
cell.setCellValue(value.toString());

currentRow++;
return currentRow;
}

0 个答案:

没有答案