无法将图像插入Excel工作表

时间:2013-08-19 10:23:25

标签: java android excel apache-poi

您好我正在尝试将图像插入到Android中的excel中,使用以下代码但无法执行此操作,请帮助!!

//创建一个路径,我们将对象列表放在外部//存储

               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 个答案:

答案 0 :(得分:1)

按照:

        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();
        }

此处start是图像左上角的起始单元格引用。同样,end是图像左上角的结束单元格引用。

CellReference start;
CellReference end;

并注意这一点。     //创建绘图族长。这是所有形状的顶级容器。

Drawing drawing = sheet.createDrawingPatriarch();

警惕使用此代码。如果在同一张纸中插入图像,则此代码每次都会创建新的Patriarch以插入新的图片/图像。确保第二次插入图像时,此代码会为要进行插入的特定工作表选择旧的Patriarch对象。