Developer01561315
Developer01561315

Reputation: 83

Java POI - convert Workbook to File

I need to return a Workbook but converted to Java File object. For now I only know how to write the Workbook to the disk with workbook.write(outputStream). However, I want to return the File object in order to use it directly for further processing (uploading to Amazon).

My code:

public File addErrorColumnToExcel(MultipartFile file, HashMap<Integer, String> errors, int newColumnIndex) throws IOException {
    Workbook workbook = null;
    Sheet sheet = null;
    Row row;
    Cell newErrorCell;
    String errorText;

    try {
      workbook = new XSSFWorkbook(new BufferedInputStream(file.getInputStream()));
      sheet = workbook.getSheetAt(FIRST_SHEET_INDEX);
    } catch (IOException e) {
      logger.error("cannot get the file: " + file.getOriginalFilename() + e);
    }

    //do some logic

    return workbook; //but I need to convert this to a java File
  }

Upvotes: 2

Views: 13564

Answers (1)

Matt
Matt

Reputation: 13923

You can create a temporary file and write the data to this file before returning it. Don't forget to delete the file after processing. Here is a simplified snippet:

public File getEmptyExcelFile() throws IOException {
    try (Workbook workbook = new XSSFWorkbook()) {

        workbook.createSheet("test"); // do some logic

        File outputFile = File.createTempFile("temp", ".xlsx");
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            workbook.write(fos);
        }
        return outputFile;
    }
}

Note that I use try-with-resources for the XSSFWorkbook and FileOutputStream.


Another idea would be to return a byte array byte[] instead of a File. This is a somewhat cleaner solution and does not write the file to the disk.

public byte[] getEmptyExcelFileAsBytes() throws IOException {
    try (Workbook workbook = new XSSFWorkbook()) {

        workbook.createSheet("test"); // do some logic

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        return baos.toByteArray();
    }
}

Upvotes: 9

Related Questions