2016-08-02 95 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