1. 程式人生 > >java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream

java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream

異常資訊:
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:75)
    at com.eshore.framework.utils.html2word.HtmlDelUtil.resolveOnlyTextKlp(HtmlDelUtil.java:229)
    at com.eshore.framework.utils.html2word.HtmlDelUtil.main(HtmlDelUtil.java:280)

在建立Workbook時使用HSSFWork讀取xls檔案字尾時出現過,切換為WorkbookFactory.creat(new FileInputStream("xx"));
異常資訊:
Unable to read entire header; 0 bytes read; expected 512 bytes 

方法程式碼如下:

private static void resolveOnlyTextKlp(){
    String localFilePath = "E:\\extractKlp\\bak\\onlyTextKlp.xlsx";
    int circleNum = 10;
    int excelIndex = 1;
    FileInputStream input = null;
    FileOutputStream output = null;
    try {
        input = new FileInputStream(new File(localFilePath));
        output = new FileOutputStream(new File(localFilePath));
        
        Workbook workbook = WorkbookFactory.create(input);
        Sheet klpSheet = workbook.getSheetAt(0);
        
        for(int i=0;i<circleNum;i++){
            //追加至excel文件中
            Row writeRow = klpSheet.createRow(excelIndex++);
            Cell cell_1 = writeRow.createCell(0);
            Cell cell_2 = writeRow.createCell(1);
            Cell cell_3 = writeRow.createCell(2);
            //知識標題
            cell_1.setCellValue("標題oo"+i);
            //知識型別
            cell_2.setCellValue("型別oo"+i);
            //知識內容
            cell_3.setCellValue("內容oo"+i);
        }
//        output = new FileOutputStream(new File(localFilePath));
        workbook.write(output);
        output.flush();
    }catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(input!=null)input.close();
            if(output!=null)output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面我同時建立輸入輸入流就會出現該錯誤Your InputStream was neither an OLE2 stream, nor an OOXML stream
解決辦法:
    將上面的output註釋開啟下面的output;即不在建立Workbook之前建立多個對同一個檔案處理的流物件。
    有錯請指正,一同學習進步!