excelasposecreateoleobject

How to add image file as Ole object in excel using java


I tried with Aspose cell. But I am able to add pdf file properly. When I add jpg file, it shows in the excel file but doesnot get opened.

I tried with following way.

sheet.getOleObjects().get(oleObjectIndex).setImageData(binary);
            sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);
            sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);

Here image shown like a thumbnail , but I dont want that.

sheet.getOleObjects().get(oleObjectIndex).setObjectData(binary);
            //sheet.getOleObjects().get(oleObjectIndex).setFileType(oleFileType);
            sheet.getOleObjects().get(oleObjectIndex).setDisplayAsIcon(true);
            sheet.getOleObjects().get(oleObjectIndex).setLeftCM(oleObjectIndex);

Here it shows proper icon for the file but file does not get opened when double clicked.

Help from the community is highly apraciated. Thank you.


Solution

  • See the following two lines of code that you also need to add:

    sheet.getOleObjects().get(oleObjectIndex).setFileFormatType(FileFormatType.UNKNOWN);
    sheet.getOleObjects().get(oleObjectIndex).setObjectSourceFullName(path);
    

    Here is complete sample code that I tested and it works fine: e.g

    Sample code:

    // Get the image file.
    String path = "e:\\test\\myfile.jpg";
    File file = new File(path);
    
    // Get the picture into the streams.
    byte[] img = new byte[(int) file.length()];
    FileInputStream fis = new FileInputStream(file);
    fis.read(img);
    
    // Instantiate a new Workbook.
    Workbook wb = new Workbook();
    
    // Get the first worksheet.
    Worksheet sheet = wb.getWorksheets().get(0);
    
    // Add an Ole object into the worksheet with the image shown in MS Excel.
    int oleObjIndex = sheet.getOleObjects().add(14, 3, 200, 220, img);
    OleObject oleObj = sheet.getOleObjects().get(oleObjIndex);
    
    // Set embedded ole object data and other attributes.
    oleObj.setObjectData(img);
    oleObj.setDisplayAsIcon(true);
    oleObj.setFileFormatType(com.aspose.cells.FileFormatType.UNKNOWN);
    oleObj.setObjectSourceFullName(path);
    
    // Save the excel file
    wb.save("f:\\files\\tstoleobject1.xlsx");
    

    Hope, this helps a bit.

    PS. I am working as Support developer/ Evangelist at Aspose.