Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get excel picture dimension using apache poi
/**
* 获取图片大小
*/
public static Dimension getDimensionFromAnchor(Picture picture) {
ClientAnchor anchor = picture.getClientAnchor();
boolean isHSSF = (anchor instanceof HSSFClientAnchor);
Sheet sheet = picture.getSheet();
double w = 0;
int col2 = anchor.getCol1();
//space in the leftmost cell
if(anchor.getCol1() != anchor.getCol2()) {
w = sheet.getColumnWidthInPixels(col2++);
if (isHSSF) {
w *= 1 - anchor.getDx1()/1024d;
} else {
w -= anchor.getDx1()/(double)EMU_PER_PIXEL;
}
while(col2 < anchor.getCol2()){
w += sheet.getColumnWidthInPixels(col2++);
}
if (isHSSF) {
w += sheet.getColumnWidthInPixels(col2) * anchor.getDx2()/1024d;
} else {
w += anchor.getDx2()/(double)EMU_PER_PIXEL;
}
} else {
if(isHSSF) {
w = sheet.getColumnWidthInPixels(col2) * (anchor.getDx2() - anchor.getDx1())/1024d;
} else {
w = (anchor.getDx2() - anchor.getDx1()) / (double)EMU_PER_PIXEL;
}
}
double h = 0;
int row2 = anchor.getRow1();
if(anchor.getRow1() != anchor.getRow2()) {
h = getTrueRowHeightInPixels(sheet,row2++);
if (isHSSF) {
h *= 1 - anchor.getDy1()/256d;
} else {
h -= anchor.getDy1()/(double)EMU_PER_PIXEL;
}
while(row2 < anchor.getRow2()){
h += getTrueRowHeightInPixels(sheet,row2++);
}
if (isHSSF) {
h += getTrueRowHeightInPixels(sheet,row2) * anchor.getDy2()/256;
} else {
h += anchor.getDy2()/(double)EMU_PER_PIXEL;
}
} else {
if(isHSSF) {
h = getTrueRowHeightInPixels(sheet,row2) * (anchor.getDy2() - anchor.getDy1())/256;
} else {
h = (anchor.getDy2() - anchor.getDy1()) / (double)EMU_PER_PIXEL;
}
}
return new Dimension((int)Math.rint(w), (int)Math.rint(h));
}
public static double getTrueRowHeightInPixels(Sheet sheet, int rowNum) {
Row r = sheet.getRow(rowNum);
double points = (r == null) ? sheet.getDefaultRowHeightInPoints() : r.getHeightInPoints();
return Units.toEMU(points)/(double)EMU_PER_PIXEL; //在线文档的最小行高是23
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment