HoseinPanahi
HoseinPanahi

Reputation: 591

using Java temporary file for XLSX Apache poi

.hi, i am trying to create a temporary .xlsx file and write to it using apache poi. i am getting EmptyFileException for creating workbook. this is the code:

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

        //...

it works fine if i use a real file. but for temp file it doesn't work. please help me with this. thanks

Upvotes: 1

Views: 7000

Answers (2)

centic
centic

Reputation: 15890

When you create a new file you will not need a file first, you can just start with a new Workbook:

Workbook wb = new XSSFWorkbook();

and then use the API to populate it. At the end you can write it to a new file via

try (OutputStream stream = new FileOutputStream(file)) {
    wb.write(stream);
}

Upvotes: 1

zerode
zerode

Reputation: 31

WorkbookFactory.create API needs an InputStream which supports mark or reset. You should try using BufferedInputStream. Note that WorkbookFactory.create(java.io.File file is recommended as it has smaller memory footprint.

Upvotes: 0

Related Questions