Открыть Excel файл после формирования
Есть класс, который формирует 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);
}
}
}
Источник: Stack Overflow на русском