简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM