Открыть Excel файл после формирования

Рейтинг: -2Ответов: 1Опубликовано: 19.04.2023

Есть класс, который формирует Excel файл из данных, получаемых из БД. Сейчас файл сохраняется в диск в какую-то папку. Как сделать, чтобы файл формировался и сразу открывался не сохраняя в файл?

@Service
public class ReportsClass {
    private XSSFWorkbook workbook;
    private XSSFSheet sheet;

    private final ItemsService itemsService;
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    @Autowired
    public ReportsClass(ItemsService itemsService) {
        this.itemsService = itemsService;
        workbook = new XSSFWorkbook();
    }

    public void getAllUsl() {
        List<Item> list = itemsService.getList();
        generateExcelFile(list);
    }

    private void writeHeader() {
        sheet = workbook.createSheet("Items");
        Row row = sheet.createRow(0);
        CellStyle style = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontHeight(11);
        style.setFont(font);
        createCell(row,0, "fam", style);
        createCell(row,1, "im", style);
        createCell(row,2, "ot", style);
        createCell(row,3, "dat_rojd", style);
        createCell(row,4, "tarif", style);
    }

    private void createCell(Row row, int columnCount, Object valueOfCell, CellStyle style) {
        sheet.autoSizeColumn(columnCount);
        Cell cell = row.createCell(columnCount);
        if (valueOfCell instanceof Integer) {
            cell.setCellValue((Integer) valueOfCell);
        } else if (valueOfCell instanceof Long) {
            cell.setCellValue((Long) valueOfCell);
        } else if (valueOfCell instanceof String) {
            cell.setCellValue((String) valueOfCell);
        } else if (valueOfCell instanceof LocalDate) {
            cell.setCellValue((LocalDate) valueOfCell);
        } else if (valueOfCell instanceof Double) {
            cell.setCellValue((Double) valueOfCell);
        } else {
            cell.setCellValue((Boolean) valueOfCell);
        }
        cell.setCellStyle(style);
    }

    private void write(List<Item> list) {
        int rowCount = 1;
        CellStyle style = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setFontHeight(11);
        style.setFont(font);

        for (Item item : list) {
            Row row = sheet.createRow(rowCount++);
            int columnCount = 0;
            createCell(row, columnCount++, item.getFam(), style);
            createCell(row, columnCount++, item.getIm(), style);
            createCell(row, columnCount++, item.getOt(), style);
            createCell(row, columnCount++, item.getDat_rojd().format(formatter), style);
            createCell(row, columnCount++, item.getTarif(), style);
        }
    }

    private void generateExcelFile(List<Item> list) {
        try (FileOutputStream outputStream = new FileOutputStream(AppConstants.filePath + "test.xlsx");
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
            writeHeader();
            write(list);
            workbook.write(bufferedOutputStream);
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

Ответы

▲ 0

Следует переписать сервис, чтобы он генерировал и возвращал экземпляр Workbook, который судя по всему может быть закэширован.

Вариант реализации (код не тестировался):

@Service
public class ReportsClass {
    @Autowired
    private final ItemsService itemsService;

    private Workbook workbook = null;

    public Workbook getAllUsl() {
        
        if (null == this.workbook) {
            this.workbook = generateWorkbook(itemsService.getList());
        }
        return this.workbook;
    }

    private Workbook generateWorkbook(List<Item> list) {
        Workbook book = new XSSFWorkbook();

        Sheet sheet = writeHeader(book);
        write(book, sheet, list);

        return book;
    }

    private Sheet writeHeader(Workbook book) {
        Sheet sheet = book.createSheet("Items");
        Row row = sheet.createRow(0);
        CellStyle style = book.createCellStyle();
        Font font = book.createFont();
        font.setBold(true);
        font.setFontHeight(11);
        style.setFont(font);
        createCell(sheet, row, 0, "fam", style);
        createCell(sheet, row, 1, "im", style);
        createCell(sheet, row, 2, "ot", style);
        createCell(sheet, row, 3, "dat_rojd", style);
        createCell(sheet, row, 4, "tarif", style);

        return sheet;
    }

    private void createCell(Sheet sheet, Row row, int columnCount, Object valueOfCell, CellStyle style) {
        sheet.autoSizeColumn(columnCount);
        Cell cell = row.createCell(columnCount);
        if (valueOfCell instanceof Integer) {
            cell.setCellValue((Integer) valueOfCell);
        } else if (valueOfCell instanceof Long) {
            cell.setCellValue((Long) valueOfCell);
        } else if (valueOfCell instanceof String) {
            cell.setCellValue((String) valueOfCell);
        } else if (valueOfCell instanceof LocalDate) {
            cell.setCellValue((LocalDate) valueOfCell);
        } else if (valueOfCell instanceof Double) {
            cell.setCellValue((Double) valueOfCell);
        } else {
            cell.setCellValue((Boolean) valueOfCell);
        }
        cell.setCellStyle(style);
    }

    private void write(Workbook book, Sheet sheet, List<Item> list) {
        int rowCount = 1;
        CellStyle style = book.createCellStyle();
        Font font = book.createFont();
        font.setFontHeight(11);
        style.setFont(font);

        for (Item item : list) {
            Row row = sheet.createRow(rowCount++);
            int columnCount = 0;
            createCell(sheet, row, columnCount++, item.getFam(), style);
            createCell(sheet, row, columnCount++, item.getIm(), style);
            createCell(sheet, row, columnCount++, item.getOt(), style);
            createCell(sheet, row, columnCount++, item.getDat_rojd().format(formatter), style);
            createCell(sheet, row, columnCount++, item.getTarif(), style);
        }
    }
}