当我将多个图像插入 Excel 工作表时,单元格中的图像对齐出现问题。工作表类型为 XSSFSheet。当我设置anchor1.setDx1和anchor.setDx2的值时,它们没有响应。
private void drawImageOnExcelSheet(XSSFSheet sheet, int row, int row2, int col, int col2, int pictureIdx) throws Exception {
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor1 = helper.createClientAnchor();
anchor1.setRow1(row); // second anchor determines bottom right position
anchor1.setRow2(row2);
anchor1.setCol1(col);
anchor1.setCol2(col2);
Picture pic = drawing.createPicture(anchor1, pictureIdx);
}`
`String imagesource = valuehandler.extractCountry(country) + ".png";
InputStream inputStream1 = new FileInputStream(dir + "\\Flags\\" + imagesource);
byte[] inputImageBytes1 = IOUtils.toByteArray(inputStream1);
int inputImagePictureID1 = wb.addPicture(inputImageBytes1, Workbook.PICTURE_TYPE_PNG);
inputStream1.close();
try {
drawImageOnExcelSheet((XSSFSheet) sheet1, h, h+1, 0, 1, inputImagePictureID1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
` }
```
[enter image description here][1]
[1]: https://i.stack.imgur.com/CUGQV.png
您考虑过使用JXLS吗?
JXLS 是 Apache POI 的一个小型包装器,它允许您使用 Microsoft Excel 定义模板,而不是在 Java 代码中执行所有操作。您的模板中有一小部分标记(for 循环、值占位符等),但大多数表示逻辑(例如颜色、粗体、页眉、页脚、图像等)都可以在 Excel 中完成。
例如你可以使用
jx:foreach(items="employees" var="employee" lastCell="D4")
和
x:image(lastCell="D10" src="_employee.country" imageType="PNG")
和
List<Employee> employees = List.of(
new Employee("foo", "france"),
new Employee("bar", "england"),
new Employee("bza", "france")
);
Set<String> uniqueCountries = employees.stream().map(Employee::getCountry).toSet();
context.putVar("employees", employees);
for (String country : uniqueCountries) {
String path = dir + /flags/" + country + ".png"
byte[] imageBytes = Util.toByteArray(new FileInputStream(path));
context.putVar(country, imageBytes);
}