I needed to initialize about 500 cells for the Excel table and then fill them. I did the initialization through the array.

private void write(String PATH) { try { InputStream inp = new FileInputStream(PATH + "\\workbook.xlsx"); Workbook wb = null; try { wb = WorkbookFactory.create(inp); } catch (EncryptedDocumentException | InvalidFormatException e) { e.printStackTrace(); } Sheet sheet = wb.getSheetAt(1); int rowCounter = 0; Cell[] mas = new Cell[500]; List<Cell> cellList = new LinkedList<Cell>(); for (int i = 0; i < getFinishFile().size(); i++) { Row row = sheet.createRow(rowCounter++); for (int j = 0; i < mas.length; i++) { mas[i] = row.createCell(j); cellList.add(mas[i]); } int j = 0; for (Cell c : cellList) { c.setCellValue(getFinishFile().get(i)[j]); j++; } } FileOutputStream fileOut = new FileOutputStream(PATH + "\\workbook.xlsx"); wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } 

But can it be done somehow faster and more locally?

  • And why do you need this Cell [] mas? If you use it only to insert into the sheet? - Roman Danilov
  • did not quite understand the comment. Yes, I use it only to insert into the sheet. and what is wrong in that case? - Padawan
  • I do not understand why you need it. Why not add directly? Without this array - Roman Danilov
  • Well, I realized that the process of writing data to a cell is 1. row.createCell (j) - create a cell, 2. then add the value setCellValue (...]) to it - Padawan

1 answer 1

If I understood everything correctly, then something like this is done:

 private static final LENGTH = 500 private void write(String PATH) { try { InputStream inp = new FileInputStream(PATH + "\\workbook.xlsx"); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(1); for (int i = 0; i < getFinishFile().size(); i++) { Row row = sheet.createRow(i); for (int j = 0; j < LENGTH; j++) { row.createCell().setCellValue(getFinishFile().get(i)[j]) } } FileOutputStream fileOut = new FileOutputStream(PATH + "\\workbook.xlsx"); wb.write(fileOut); fileOut.close(); } catch (EncryptedDocumentException | IOException e | InvalidFormatException e) { e.printStackTrace(); } } 

You can still rewrite the cycles through IntStream, but I think that is normal.

  • thank. at the expense of IntStream I read. - Padawan