Apache poi : how to add image to sheet

Sharing Knowledge

In this post I want just to share the code how to add or insert an image in spreadsheet like (MS Excel) using the Apache poi API. When I work in a project I’ve the following use cases :

  1. In every generated (Excel) report, the application’s logo must be inserted in the top-left corner
  2. The logo must take 3 lines and 5 columns, and the top-left corner of the logo must be in specified (x,y).

The code source :

private static void insertImageWithFilename(Workbook workbook, HSSFSheet sheet, int col,
            int row, double scaling, String fileName) {
        try {

            InputStream is = new FileInputStream(fileName);
            byte[] bytes = IOUtils.toByteArray(is);
            int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();


View original post 68 mots de plus

Par défaut