apache poi写入临时文件而不是真实文件

时间:2016-08-02 14:18:17

标签: java apache-poi

我有一个excel文件作为模板,将由多个用户编写和下载

我正在使用apache poi来做这件事 问题是当一个用户填写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;

1 个答案:

答案 0 :(得分:2)

我终于找到了解决问题的解决方案

似乎无论何时我在工作簿上调用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(); } 方法,它都会自动将文件保存在库中编码的硬盘上

File

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

只有在向工作簿提供OPCPackageInputStream时才会发生这种情况 解决方案是使用XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(file));FOR ................. DO ( (YOUR_CONDITION && echo "YES" ) || (echo "NO") ) ,它不会覆盖我想要的模板