I have an image and some text below the image in an excel sheet. when i am applying autoSizeColumn() to the column where text present the image is also getting streched . i am also setting the anchortype to 2 but this is not protecting the image to resize. I am posting some sample code here.
public static void main(String[] args) {
try{
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet sheet = book.createSheet("Test Sheet");
InputStream is = new FileInputStream("D:\\RPM_Eclipse_Workspaces\\B6.9\\00POI\\Chrysanthemum.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = book.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 255, 2,2,10,10);
//Image should not get Resized while doing Autosize
anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
Picture pict = drawing.createPicture(anchor, pictureIdx);
XSSFRow row = sheet.createRow(12);
for(int i = 2 ; i < 11 ; i++){
XSSFCell cell = row.createCell(i);
cell.setCellValue("oval (although anchor's type is set to MOVE_DONT_RESIZE ). ... But the one way to ");
}
sheet.autoSizeColumn(2);
book.write(new FileOutputStream(new File("D:\\auto.xlsx")));
System.out.println("=== DONE ===");
}catch (Exception e){
}
}
In picture.resize () method, to calculate the original height of the image, it use the row.getHeight value. The problem is, the row height value ! Depending on the contents of the cell, the row height is increased automatically, but you cannot obtain the increased height value by row.getHeight() method. So, you need to set the height of row using row.setHeigth (height) manually. then you can be obtained for the normal image size and the picture.resize () method will work properly.
POI uses
TwoCellAnchors
for adding pictures ... so with a bit of nasty reflections, you can add a Picture with aOneCellAnchor
In the example the
drawing.createAnchor(10, 10, 110, 110, 2, 2, 0, 0)
is used to position the image 10x10 from the top left corner of the cell(2,2) and scale the picture to 100x100 pixels, i.e. 110-10.(tested with Libre Office 4.0, Excel Viewer 2010)