Gin*_*nso 1 java excel image apache-poi
您好,我使用 POI 创建了 excel 表。我以下一种方式添加了图片(jpg文件):
Workbook wb = new HSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
//...
InputStream is = new FileInputStream("img.jpg");
byte[] bytes = IOUtils.toByteArray(is);
int picIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(5);
anchor.setRow1(5);
Picture pict = drawing.createPicture(anchor, picIdx);
pict.resize();
Run Code Online (Sandbox Code Playgroud)
现在我希望图片适合该单元格,但我不想更改其纵横比。我可以调整大小的比例是关于单元格的,显然可以有不同的比例。我试图计算比例,但问题是,我无法以像素为单位获取或设置行高,只能以 pt 为单位,而且我无法计算单元格比率,因为我无法获得宽度和高度同一单位...有什么建议吗?
小智 5
POI 中有一个Units类,它提供像素和点之间的转换。
这里有一些方法可能有助于设置单元格的宽度和高度。
1.厘米到像素
public static int cmToPx(double cm) {
return (int) Math.round(cm * 96 / 2.54D);
}
Run Code Online (Sandbox Code Playgroud)
96是我的显示器的 DPI(从dpilove检查你的)
和 1 英寸 = 2.54 厘米
2.厘米到行高
public static int cmToH(double cm) {
return (int) (Units.pixelToPoints(cmToPx(cm)) * 20); //POI's Units
}
Run Code Online (Sandbox Code Playgroud)
用法:sheet.setDefaultRowHeight(cmToH(1.0))
参考:HSSFRow#getHeightInPoints
以“缇”或点的 1/20 为单位设置高度。
3.厘米到列宽
public static int cmToW(double cm) {
return (int) Math.round(((cmToPx(cm) - 5.0D) / 8 * 7 + 5) / 7 * 256);
}
Run Code Online (Sandbox Code Playgroud)
使用方法:sheet.setColumnWidth(cmToW(1.0))
使用(px - 5.0D) / 8。从像素转换为点在Excel宽度(当拖动列在Excel的宽度,像素和点会显示在你的光标)
参考:HSSFSheet#setColumnWidth
设置宽度(以字符宽度的 1/256 为单位)
Excel 使用以下公式(OOXML 规范的第 3.3.1.12 节):
// Excel width, not character width
width = Truncate([{Number of Visible Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width} * 256) / 256
Run Code Online (Sandbox Code Playgroud)
以 Calibri 字体为例,11 磅字体大小的最大数字宽度为 7 像素(96 dpi)。如果您将列宽设置为 8 个字符宽,例如 setColumnWidth(columnIndex, 8*256),则可见字符的实际值(Excel 中显示的值)由以下等式得出:
Truncate([numChars * 7 + 5] / 7 * 256) / 256 = 8;
Run Code Online (Sandbox Code Playgroud)
使用 XSSFClientAnchor 调整图片大小以填充单元格并保持其比例:
// Excel width, not character width
width = Truncate([{Number of Visible Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width} * 256) / 256
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7146 次 |
| 最近记录: |