Сохранить данные в Excel
Есть сервис, который сохраняет данные из List в файл Excel. Проблема в том, что даже небольшой объем данных примерно 1000 записей сохраняется очень долго. Подскажите, пожалуйста, можно ли как-то оптимизировать мой код?
@Service
public class ReportsItem {
private XSSFWorkbook workbook;
private XSSFSheet sheet;
@Autowired
public ReportsItem() {
workbook = new XSSFWorkbook();
}
public void getAllItems(List<Item> list) {
generateItemExcelFile(list);
}
//Метод создает заголовки в Excel документе
private void writeItemsHeader() {
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, "desc", style);
createCell(row,1, "number", style);
createCell(row,2, "fio", style);
createCell(row,3, "birthDate", style);
createCell(row,4, "date_in", style);
createCell(row,5, "date_out", style);
createCell(row,6, "refreason", style);
createCell(row,7, "price", style);
createCell(row,8, "service", style);
createCell(row,9, "allsum", style);
createCell(row,10, "type", style);
createCell(row,11, "razdel", style);
createCell(row,12, "sotrcode", style);
createCell(row,13, "idnum", style);
createCell(row,14, "idhistory", style);
createCell(row,15, "comment", style);
}
//Метод записывает в Excel
private void writeItems(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.getDesc(), style);
createCell(row, columnCount++, item.getNumber(), style);
createCell(row, columnCount++, item.getFio(), style);
createCell(row, columnCount++, item.getBirthDate(), style);
createCell(row, columnCount++, item.getDate_in(), style);
createCell(row, columnCount++, item.getDate_out(), style);
createCell(row, columnCount++, item.getRefreason(), style);
createCell(row, columnCount++, item.getPrice(), style);
createCell(row, columnCount++, item.getService(), style);
createCell(row, columnCount++, item.getAllSum(), style);
createCell(row, columnCount++, item.getType(), style);
createCell(row, columnCount++, item.getRazdel(), style);
createCell(row, columnCount++, item.getSotrcode(), style);
createCell(row, columnCount++, item.getIdnum(), style);
createCell(row, columnCount++, item.getNhistory(), style);
createCell(row, columnCount++, item.getComment(), 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 if (valueOfCell instanceof Boolean){
cell.setCellValue((Boolean) valueOfCell);
}
cell.setCellStyle(style);
}
//Сохраняем файл в Excel формат
private void generateItemExcelFile(List<Item> list) {
String fileName = "report-" + LocalDate.now() + ".xlsx";
File dir = new File(AppConstants.reportsFilePath);
if (!dir.exists()) {
dir.mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(AppConstants.reportsFilePath + fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
writeItemsHeader();
writeItems(list);
workbook.write(bufferedOutputStream);
workbook.close();
AlertDialogUtils.showInfoAlert("Информация", null, "Файл отчета успешно сформирован в: " + AppConstants.reportsFilePath + fileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Ответы (1 шт):
Автор решения: Kolhoznik
→ Ссылка
Сделал так, быстрее стало работать.
@Service
public class ReportsItem {
private SXSSFWorkbook workbook;
private SXSSFSheet sheet;
@Autowired
public ReportsItem() {
workbook = new SXSSFWorkbook();
}
public void getAllItems(List<Item> list) {
generateItemExcelFile(list);
}
//Метод создает заголовки в Excel документе
private void writeItemsHeader() {
sheet = workbook.createSheet("Items");
SXSSFRow row = sheet.createRow(0);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeight(11);
style.setFont(font);
createCell(row,0, "desc", style);
createCell(row,1, "number", style);
createCell(row,2, "fio", style);
createCell(row,3, "birthDate", style);
createCell(row,4, "date_in", style);
createCell(row,5, "date_out", style);
createCell(row,6, "refreason", style);
createCell(row,7, "price", style);
createCell(row,8, "service", style);
createCell(row,9, "allsum", style);
createCell(row,10, "type", style);
createCell(row,11, "razdel", style);
createCell(row,12, "sotrcode", style);
createCell(row,13, "idnum", style);
createCell(row,14, "idhistory", style);
createCell(row,15, "comment", style);
}
//Метод записывает в Excel
private void writeItems(List<Item> list) {
int rowCount = 1;
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
style.setFont(font);
for (Item item : list) {
SXSSFRow row = sheet.createRow(rowCount++);
int columnCount = 0;
createCell(row, columnCount++, item.getDesc(), style);
createCell(row, columnCount++, item.getNumber(), style);
createCell(row, columnCount++, item.getFio(), style);
createCell(row, columnCount++, item.getBirthDate(), style);
createCell(row, columnCount++, item.getDate_in(), style);
createCell(row, columnCount++, item.getDate_out(), style);
createCell(row, columnCount++, item.getRefreason(), style);
createCell(row, columnCount++, item.getPrice(), style);
createCell(row, columnCount++, item.getService(), style);
createCell(row, columnCount++, item.getAllSum(), style);
createCell(row, columnCount++, item.getType(), style);
createCell(row, columnCount++, item.getRazdel(), style);
createCell(row, columnCount++, item.getSotrcode(), style);
createCell(row, columnCount++, item.getIdnum(), style);
createCell(row, columnCount++, item.getNhistory(), style);
createCell(row, columnCount++, item.getComment(), style);
}
}
//Метод создает ячейку
private void createCell(SXSSFRow row, int columnCount, Object valueOfCell, CellStyle style) {
SXSSFCell 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 if (valueOfCell instanceof Boolean){
cell.setCellValue((Boolean) valueOfCell);
}
cell.setCellStyle(style);
}
//Сохраняем файл в Excel формат
private void generateItemExcelFile(List<Item> list) {
String fileName = "report-" + LocalDate.now() + ".xlsx";
File dir = new File(AppConstants.reportsFilePath);
if (!dir.exists()) {
dir.mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(AppConstants.reportsFilePath + fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
writeItemsHeader();
writeItems(list);
workbook.write(bufferedOutputStream);
workbook.close();
AlertDialogUtils.showInfoAlert("Информация", null, "Файл отчета успешно сформирован в: " + AppConstants.reportsFilePath + fileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}