为xlsx ApachePOI使用Java临时文件

2022-08-15 00:00:00 excel xlsx temporary-files java apache-poi

.hi,我正在尝试创建一个临时的.xlsx文件,并使用ApachePOI对其进行写入。我正在获取用于创建工作簿的EmptyFileException。代码如下:

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);
        }

        //...

如果我使用真实的文件,它工作得很好。但对于临时文件,它不起作用。请帮我拿一下这个。谢谢


解决方案

创建新文件时,首先不需要文件,只需从新工作簿开始:

Workbook wb = new XSSFWorkbook();

,然后使用API填充它。最后,您可以通过

将其写入新文件
try (OutputStream stream = new FileOutputStream(file)) {
    wb.write(stream);
}

相关文章