2016-08-02 92 views
1

我有作爲一個模板,將幾個用戶的Apache POI寫入臨時文件,而不是真正的文件

我使用的Apache POI這樣做
的問題進行創作的,並下載一個excel文件,當一個用戶填寫excel(使用gui客戶端)它將直接寫入模板,但作爲模板,它應該保持未修改,否則下一個用戶將有以前的用戶更改....

我認爲最好的解決方案是寫到臨時文件將在用戶的行動出口刪除

非常感謝您

 File excelFile = openTemplate(); 
     OPCPackage pkg = OPCPackage.open(excelFile ,PackageAccess.READ_WRITE); 
     XSSFWorkbook book = new XSSFWorkbook(pkg); 
     book.setWorkbookType(XSSFWorkbookType.XLSX); 
     book.setForceFormulaRecalculation(true); 

     // excel treatments (sheet , styles etc..) 

     FileOutputStream out = 
       new FileOutputStream(TempFile.createTempFile("Export" , ".xlsx")); 
     book.write(out); 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bos.writeTo(out); 
     bytes = bos.toByteArray(); 
     out.close(); 
     bos.close(); 
     book.close(); 
     return bytes; 
+0

你應該叫'bos.close()''之前bos.toByteArray()'。 –

+0

您似乎正在寫入'ByteArrayOutputStream'而不是作爲臨時文件創建的'File' - 當您更改代碼以實際寫入臨時文件時會發生什麼? – Gagravarr

+0

@beckyang謝謝,代碼已更新 – ulquiorra

回答

2

我終於設法找到了一種解決我的問題的解決方案

看來,每當我打電話close方法在工作簿時,它會自動保存在硬盤中的文件,如編碼圖書館

public void close() throws IOException { 
     if (this.packageAccess == PackageAccess.READ) { 
      logger.log(POILogger.WARN, 
        "The close() method is intended to SAVE a package. This package is open in READ ONLY mode, use the revert() method instead !"); 
      revert(); 
      return; 
     } 
     if (this.contentTypeManager == null) { 
      logger.log(POILogger.WARN, 
        "Unable to call close() on a package that hasn't been fully opened yet"); 
      return; 
     } 

     // Save the content 
     ReentrantReadWriteLock l = new ReentrantReadWriteLock(); 
     try { 
      l.writeLock().lock(); 
      if (this.originalPackagePath != null 
        && !"".equals(this.originalPackagePath.trim())) { 
       File targetFile = new File(this.originalPackagePath); 
       if (!targetFile.exists() 
         || !(this.originalPackagePath 
           .equalsIgnoreCase(targetFile.getAbsolutePath()))) { 
        // Case of a package created from scratch 
        save(targetFile); 
       } else { 
        closeImpl(); 
       } 
      } else if (this.output != null) { 
       save(this.output); 
       output.close(); 
      } 
     } finally { 
      l.writeLock().unlock(); 
     } 

     // Clear 
     this.contentTypeManager.clearAll(); 
    } 

http://apache-poi.1045710.n5.nabble.com/Validating-office-files-without-saving-them-td5722653.htmlhttps://bz.apache.org/bugzilla/show_bug.cgi?id=59287

它只有當發生FileOPCPackage提供給工作簿。
解決的辦法是用InputStream工作:XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(file));這將不會覆蓋模板,因爲我想

+0

面對同樣的概率,簡單的解決方案,謝謝! – Dmitry