问题描述
以下代码在我的本地机器上运行良好。但它在服务器上不起作用 - 可能是因为权限。 我可以在不实际在服务器上创建文件的情况下完成这项工作吗?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(Constants.SHEET_NAME);
for (Integer serialNo : reportReq.getSerialNos()) {
TraitsExceptionReport report = traitsExceptionReport.get(serialNo - 1);
Row row = sheet.createRow(rownum++);
createList(report,row);
}
File file = new File(Constants.TMP_FILE_NAME);
String absolutePath = file.getAbsolutePath();
FileOutputStream out = new FileOutputStream(file);
workbook.write(out);
FileInputStream fis = new FileInputStream(absolutePath );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
out.close();
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf,readNum);
}
} catch (IOException ex) {
throw new IOException("Exception while creating Traits Exception Report");
}
fis.close();
Files.deleteIfExists(Paths.get(absolutePath));
return(bos.toByteArray());
开发人员必须在 unix 服务器上编写文件时遵循的标准方法是什么。
解决方法
POI 5.0.0 添加了 DeferredSXSSFWorkbook - 有点像 SXSSFWorkbook,但不需要临时文件 - 它为每个工作表使用行生成函数,当您将工作簿写出到输出流时,它会延迟执行。 我刚刚在 https://github.com/apache/poi/blob/trunk/src/examples/src/org/apache/poi/examples/xssf/streaming/DeferredGeneration.java
中添加了一个简单的示例有一些测试,您可能会从中了解其工作原理 https://github.com/apache/poi/blob/trunk/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java