使用XLSX Apache poi的Java临时文件
.hi,我正在尝试创build一个临时的.xlsx文件,并使用apache poi写入。 我得到EmptyFileException创build工作簿。 这是代码:
public class Writer{ File file; public File Write(List<FormData> l, Class elementClass) { try {//create temp fiele here file = File.createTempFile(elementClass.getSimpleName(),".xlsx"); } catch (IOException ex) { Logger.getLogger(Writer.class.getName()).log(Level.SEVERE, null, ex); } XSSFWorkbook workbook; XSSFSheet sheet; if (file.exists()) { FileInputStream inputStream; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException ex) { throw new AspirinException(AspirinException.Type.INTERNAL_ERROR); } try {// this line gets error// workbook = (XSSFWorkbook) WorkbookFactory.create(inputStream); } catch (IOException | InvalidFormatException | EncryptedDocumentException ex) { throw new AspirinException(AspirinException.Type.INTERNAL_ERROR); } //...
它工作正常,如果我使用一个真实的文件。 但临时文件不起作用。 请帮我解决一下这个。 谢谢
当你创build一个新的文件时,你将不需要一个文件,你可以从一个新的工作簿开始:
Workbook wb = new XSSFWorkbook();
然后使用API填充它。 最后,您可以通过将其写入新文件
try (OutputStream stream = new FileOutputStream(file)) { wb.write(stream); }
WorkbookFactory.create
API需要一个支持标记或重置的InputStream
。 你应该尝试使用BufferedInputStream
。 请注意,build议使用WorkbookFactory.create(java.io.File
文件,因为它具有较小的内存占用量。