0

嗨,我正在尝试将图像插入到 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);
4

1 回答 1

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 对象。

于 2013-08-19T10:34:22.750 回答