Not able to insert image into excelsheet

2019-08-28 20:11发布

Hi I am trying to insert image into excel in android, using the following code but not able to do so, please help !!

// Create a path where we will place our List of objects on external // storage

               File file = new File(context.getExternalFilesDir(null), "abc.xls");
    FileOutputStream fileOS = null;
    //add picture data to this workbook.
    InputStream is = text.getResources().getAssets().open("images.jpg");
    byte[] bytes = IOUtils.toByteArray(is);
    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    is.close();

    CreationHelper helper = wb.getCreationHelper();

    //create sheet
    Sheet sheet = wb.createSheet();

    // Create the drawing patriarch. This is the top level container for all shapes. 
    Drawing drawing = sheet.createDrawingPatriarch();

    //add a picture shape
    ClientAnchor anchor = helper.createClientAnchor();
    //set top-left corner of the picture,
    //subsequent call of Picture#resize() will operate relative to it
    anchor.setCol1(0);
    anchor.setRow1(0);
    Picture pict = drawing.createPicture(anchor, pictureIdx);

    //auto-size picture relative to its top-left corner
//  pict.resize();


//  if(wb instanceof XSSFWorkbook) file += "x";
    fileOS= new FileOutputStream(file);
    wb.write(fileOS);

1条回答
Anthone
2楼-- · 2019-08-28 20:53

Follow this:

        FileInputStream fis = new FileInputStream(imagePath);
        int b;
        byte[] bytes = IOUtils.toByteArray(fis);
        fis.close();

        // This will insert the picture from start cell to end cell of excel
        // sheet.
        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
                start.getCol(), start.getRow(), end.getCol(), end.getRow());

        anchor.setAnchorType(2);

        int index = wb.addPicture(bytes, HSSFWorkbook.PICTURE_TYPE_JPEG);

        // Create the drawing patriarch. This is the top level container for all shapes. 
        Drawing patriarch = sheet.createDrawingPatriarch();
        try {
            HSSFPicture picture = patriarch.createPicture(anchor, index);
            // picture.resize();
        } catch (Exception e) {
            String err = e.getMessage();
        }

Here start is the starting cell reference for the left-top corner of image. Similarly, end is the ending cell reference for the left-top corner of image.

CellReference start;
CellReference end;

and Note this. // Create the drawing patriarch. This is the top level container for all shapes.

Drawing drawing = sheet.createDrawingPatriarch();

Be wary of using this code. In case of Image insertion in the same sheet this code creates new Patriarch every time for new picture/image to be inserted. Make sure that for the second time image insertion this code picks the old Patriarch object for the particular sheet where insertion is to be done.

查看更多
登录 后发表回答