Apache poi 3.0.1-FINAL несколько изображений в проблему листа Excel - PullRequest
0 голосов
/ 07 мая 2020

В настоящее время я пытаюсь сделать экспорт в Excel, используя apache -poi 3.0.1-FINAL (его нельзя изменить без серьезных изменений в проекте, а бюджет этого не позволяет).

Что я хочу: -Экспортировать список изображений (изображения поступают в виде списков байтов []) в файл Excel с расширением .xls

Каково текущее поведение: - Только последнее изображение из списка отображается, остальные не находятся в файле Excel.

Это код, который я использую:

 public void execute(HSSFWorkbook wb, int sheetIndex, int startRowIndex, Object valueBean, String parametersString) {

        HSSFSheet templateSheet = wb.getSheetAt(sheetIndex);
        HSSFPatriarch patriarch = templateSheet.createDrawingPatriarch();
        HSSFRow currentRow = wb.getSheetAt(0).getRow(startRowIndex);
        HSSFCell currentCell = null;
        String cellValue = null;
        HSSFClientAnchor anchor = null;
        // String property = null;
        String[] splited = null;
        BufferedImage bi = null;
        ByteArrayOutputStream baos = null;
        byte[] byteArray = null;

        for (int cellId = 1; cellId <= currentRow.getLastCellNum(); cellId++) {
            currentCell = currentRow.getCell((short) cellId);
            if (currentCell != null) {
                // cellValue = currentCell.getStringCellValue();
                cellValue = currentCell.getRichStringCellValue().getString();
                if (cellValue != null && cellValue.length() > 0 && cellValue.indexOf(":") > -1) {

                    splited = cellValue.split(":");
                    // property = splited[0]
                    anchor = new HSSFClientAnchor(0,
                            0,
                            0,
                            0,
                            (short) cellId,
                            startRowIndex,
                            (short) (((short) cellId) + (short) Short.parseShort(splited[1].substring(0, splited[1].indexOf(",")).trim())), //find the col of the image where it ends
                            (startRowIndex + Integer.parseInt(splited[1].substring(splited[1].indexOf(",") + 1, splited[1].length()).trim()))); //find the row of the image where it ends
                    anchor.setAnchorType(2);

                    byteArray = (byte[]) BeanUtils.getProperty(valueBean, splited[0]);


                    bi = createImageFromBytes(byteArray); //convert byte[] into BufferedImage

                    try {

//this is the important part
                        baos = new ByteArrayOutputStream();
                        ImageIO.write(bi, ImageFormat.PNG, baos);
                        int index = wb.addPicture(baos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);

                        patriarch.createPicture(anchor, index);

                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    } finally {

                        try {
                            baos.flush();
                            baos.close();
                        } catch (IOException e) {
                            log.error(e.getMessage(), e);
                        }

                    }
                }
            }
        }
    }



    private BufferedImage createImageFromBytes(byte[] imageData) {
        ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
        try {
            return ImageIO.read(bais);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Согласно этой странице http://poi.apache.org/components/spreadsheet/quick-guide.html#Images означает, что он может стереть существующие изображения, но даже в этом случае, возможно, есть обходной путь или способ предотвратить это?

...