如何将XSSFWorkbook转换为文件

时间:2014-07-18 14:35:20

标签: java eclipse file

我目前有一个XSSFWorkbook,并希望将其转换或以某种方式将其更改为Java代码中的File。有没有办法这样做?

2 个答案:

答案 0 :(得分:7)

使用XSSFWorkbook.write(java.io.OutputStream stream)将内容写入文件。

FileOutputStream out = new FileOutputStream("yourFileName.xls");
Workbook wb = new XSSFWorkbook();
//do your stuff ...

wb.write(out);

答案 1 :(得分:0)

使用并测试了Bellow代码。

private Response sendExcelFile(Locale locale, Optional<List<List<String>>> consumersReportData) {
    XSSFWorkbook workBook = ExportToExcelUtils.prepareWorkBook(consumersReportData.get(), "data");



    String DisplayFileName = "Consumers-Report-" + DateUtils.getLocalDateInString(DateUtils.now());
    String fileName = "/tmp/fileName.xlsx";

// Created file object here 

    File file = new File(fileName);

    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        workBook.write(outputStream);
    } catch (FileNotFoundException e) {
        LOGGER.error("File not found : fileName {}  Exception details:{} ", fileName, e);

    } catch (IOException e) {
        LOGGER.error("IO exception  : fileName {}  Exception details:{} ", fileName, e);

    }

    ResponseBuilder responseBuilder = Response.ok((Object) file);
    responseBuilder.header("Content-Disposition", "attachment; filename=" + DisplayFileName + EXCEL_FILE_EXTENSTION);
    return responseBuilder.build();
}