// Excel width, not character width
width = Truncate([{Number of Visible Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width} * 256)/256
以Calibri字体为例,11点字体大小的最大数字宽度为7像素(96 dpi)。如果您将列宽设置为八个字符宽度,例如setColumnWidth(columnIndex,8 * 256),则可见字符(在Excel中显示的值)的实际值从下式导出: Truncate([numChars * 7 + 5]/7 * 256)/256 = 8;
使用cmToW()当设置列的宽度(字符宽度 )如sheet.setColumnWidth()
下面我设置XSSFClientAnchor来调整图片以填充细胞并保持其比。 // set padding between picture and gridlines so gridlines would not covered by the picture
private static final double paddingSize = 10;
private static final int padding = Units.toEMU(paddingSize);
public static int[] calCellAnchor(double cellX, double cellY, int imgX, int imgY) {
// assume Y has fixed padding first
return calCoordinate(true, cellX, cellY, imgX, imgY);
}
public static int[] calCoordinate(boolean fixTop, double cellX, double cellY, int imgX, int imgY) {
int x = imgX;
double ratio = ((double) imgX)/imgY;
x = (int) Math.round(Units.toEMU(cellY - 2 * paddingSize) * ratio);
x = (Units.toEMU(cellX) - x)/2;
if (x < padding) {
return calCoordinate(false, cellY, cellX, imgY, imgX);
}
return calDirection(fixTop, x);
}
public static int[] calDirection(boolean fixTop, int x) {
if (fixTop) {
return new int[] { x, padding, -x, -padding };
} else {
return new int[] { padding, x, -padding, -x };
}
}
...
// set XSSFClientAnchor here
BufferedImage img = ImageIO.read(new File(path));
int[] anchorArray = calCellAnchor(Units.pixelToPoints(cellW), Units.pixelToPoints(cellH), img.getWidth(),
img.getHeight());
XSSFClientAnchor anchor = new XSSFClientAnchor(anchorArray[0], anchorArray[1], anchorArray[2], anchorArray[3], col1, row1, col2, row2);
...