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

556 views Asked by At

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.

2

There are 2 answers

1
Amjad Sahi On BEST ANSWER

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.

1
MMMM On

i just use the same code,but i found when i open the new Excel,it shows as a image,i have to check it twice to transfer it to an OLE. whats worry