1
votes

.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

2
Which error and where / on which line ?Marged
What do you think will your file be else than an empty file? WorkbookFactory.create(inputStream) tries creating a Workbookobject containing data read from the inputStream. This fails if there is no data to read.Axel Richter
WorkbookFactory.create () is used for existing/filled Excel files. Create a XSSFWorkbook from scratch and then write () it to your tempfilekiwiwings

2 Answers

1
votes

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

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.