2013-08-19 41 views
0

嗨我想插入圖像到Excel中的Excel中,使用下面的代碼,但不能這樣做,請幫助!無法將圖像插入excelsheet

//創建,我們將會把我們的對象列表外部//保存

   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

的路徑遵循此:

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

這裏開始是左的起始單元格引用圖像的頂角。同樣,end是圖像左上角的結束單元格引用。

CellReference start; 
CellReference end; 

並注意這一點。 //創建繪圖族長。這是所有形狀的頂級容器。

Drawing drawing = sheet.createDrawingPatriarch(); 

請謹慎使用此代碼。如果在同一張圖片中插入圖片,則此代碼會在每次插入新圖片/圖片時創建新的族長。確保第二次插入圖片時,此代碼會爲要插入的特定圖紙選取舊的Patriarch對象。

+0

什麼是開始和結束? – androidDev

+0

您創建 CellReference start = new CellReference(「AB13」); CellReference end = new CellReference(「GN13」); 通過這種方式,您可以在要插入圖像的位置創建單元格引用。 – Master

+0

工作完成後,請接受其身份驗證的答案。它可以用於其他人。 – Master