Skip to content

Instantly share code, notes, and snippets.

@Leaking
Created April 10, 2018 03:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Leaking/8e0ac94aeb80800c2376f39010eac41d to your computer and use it in GitHub Desktop.
Save Leaking/8e0ac94aeb80800c2376f39010eac41d to your computer and use it in GitHub Desktop.
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