当前位置:   article > 正文

Java实现Excel中插入图片_生成的图片附到exel自动适配在exel右上角同时保留原来数据 上java

生成的图片附到exel自动适配在exel右上角同时保留原来数据 上java

废话不多说,直接上代码

1. 首先引入图片缩放所需要的依赖(如果不需要对图片进行缩放,则可以省略该步骤)

  1. <dependency>
  2. <groupId>org.imgscalr</groupId>
  3. <artifactId>imgscalr-lib</artifactId>
  4. <version>4.2</version>
  5. </dependency>

2. 主方法,网上随便找一张图片,并将生成的.xlsx文件保存到本地路径

  1. public static void main(String[] args) {
  2. Workbook workbook = new XSSFWorkbook();
  3. Sheet sheet = workbook.createSheet("测试");
  4. sheet.createRow(0);
  5. String imageUrl = "图片路径";
  6. insertImageToSheet(sheet, imageUrl, 0, 0);
  7. saveFile("/Users/xxx/Desktop/test.xlsx", workbook);
  8. }

3. 将图片插入单元格,其中,旋转图片和缩放图片可根据实际需求自行添加或删除 

  1. /**
  2. * 将图片插入单元格
  3. */
  4. private static void insertImageToSheet(Sheet sheet, String imageUrl, int rowNum, int colNum) {
  5. //1. 下载图片
  6. BufferedImage originalImage = downloadImage(imageUrl);
  7. if (Objects.isNull(originalImage)) {
  8. return;
  9. }
  10. //2. 旋转图片
  11. BufferedImage rotatedImage = rotateImage(originalImage);
  12. //3. 缩放图片
  13. ScaledImageDataDTO scaledImageData = scaleImage(rotatedImage);
  14. //4.将缩放后的图片转换为bytes
  15. byte[] imageBytes = processImageToBytes(scaledImageData.getScaledImage());
  16. //5.将图片bytes添加到Excel中
  17. setIntoSheet(sheet, rowNum, colNum, imageBytes, scaledImageData.getHeight());
  18. }
  1. @Data
  2. @AllArgsConstructor
  3. public class ScaledImageDataDTO {
  4. private int height;
  5. private BufferedImage scaledImage;
  6. }

 注:缩放图片尺寸可修改desiredWidth值自定义

  1. /**
  2. * 下载图片
  3. */
  4. private static BufferedImage downloadImage(String imageUrl) {
  5. try {
  6. URL url = new URL(imageUrl);
  7. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  8. connection.setRequestMethod("GET");
  9. connection.setConnectTimeout(5000);
  10. connection.setReadTimeout(5000);
  11. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
  12. log.error("【图片下载失败,url:{}, 链接状态码:{}】", imageUrl, connection.getResponseCode());
  13. return null;
  14. }
  15. InputStream inputStream = connection.getInputStream();
  16. BufferedImage image = ImageIO.read(inputStream);
  17. inputStream.close();
  18. return image;
  19. } catch (Exception e) {
  20. log.error("【图片下载失败,url:{}, 错误信息:{}】", imageUrl, e);
  21. return null;
  22. }
  23. }
  24. /**
  25. * 旋转图片
  26. */
  27. private static BufferedImage rotateImage(BufferedImage targetImage) {
  28. int w = targetImage.getWidth();
  29. int h = targetImage.getHeight();
  30. BufferedImage rotatedImage = new BufferedImage(h, w, targetImage.getType());
  31. Graphics2D g2d = rotatedImage.createGraphics();
  32. AffineTransform at = new AffineTransform();
  33. at.translate(h / 2.0, w / 2.0);
  34. at.rotate(Math.toRadians(270),0, 0);
  35. at.translate(-w / 2.0, -h / 2.0);
  36. g2d.drawRenderedImage(targetImage, at);
  37. g2d.dispose();
  38. return rotatedImage;
  39. }
  40. /**
  41. * 缩放图片
  42. */
  43. private static ScaledImageDataDTO scaleImage(BufferedImage targetImage) {
  44. int desiredWidth = 170; // 图片宽度
  45. double aspectRatio = (double) targetImage.getHeight() / targetImage.getWidth();
  46. int desiredHeight = (int) (desiredWidth * aspectRatio); // 保持纵横比
  47. BufferedImage scaledImage = Scalr.resize(targetImage, Scalr.Method.QUALITY, desiredWidth, desiredHeight);
  48. return new ScaledImageDataDTO(desiredHeight, scaledImage);
  49. }
  50. /**
  51. * 图片转bytes
  52. */
  53. private static byte[] processImageToBytes(BufferedImage targetImage) {
  54. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  55. try {
  56. ImageIO.write(targetImage, "png", stream);
  57. return stream.toByteArray();
  58. } catch (IOException e) {
  59. log.error("【图片转bytes异常,错误信息:】", e);
  60. return new byte[0];
  61. }
  62. }
  63. /**
  64. * 将图片bytes添加到Excel中
  65. */
  66. private static void setIntoSheet(Sheet sheet, int rowNum, int colNum, byte[] imageBytes, int imageHeight) {
  67. int pictureIdx = sheet.getWorkbook().addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
  68. CreationHelper helper = sheet.getWorkbook().getCreationHelper();
  69. Drawing<?> drawing = sheet.createDrawingPatriarch();
  70. ClientAnchor anchor = helper.createClientAnchor();
  71. anchor.setCol1(colNum);
  72. anchor.setRow1(rowNum);
  73. Picture pict = drawing.createPicture(anchor, pictureIdx);
  74. // 设置行高度以匹配图片高度
  75. Row row = sheet.getRow(rowNum);
  76. row.setHeightInPoints((float) (imageHeight * 0.75));
  77. pict.resize();
  78. }

 代码亲测有效,如有疑问欢迎留言噢~

Dependent on GPT4.0

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/272979?site
推荐阅读
相关标签
  

闽ICP备14008679号