java Excel图片在合并单元格等比缩放且居中显示

下面展示一些 内联代码片

          int x = 9;   //列总数
          int y = 8;   //行总数
          //单元格高度
          double heightRow = (cell.getRow().getHeightInPoints() / 72) * 96;    //80
           //单元格宽度
          double widthRow = sheetPicture.getColumnWidth(cell.getColumnIndex()) / 32;   //86
          byte[]  fileContentBmp = SystemUtil.fileConvertToByteArray("D:/a1.png");  测试
          if(fileContentBmp.length <= 0){   //没图片不处理
                break;
           }
           InputStream in = new ByteArrayInputStream(fileContentBmp);
           BufferedImage ms = ImageIO.read(in);
          double imageOriginalWidth = ms.getWidth();//原始图片的长度
          double imageOriginalHeight = ms.getHeight();//原始图片的宽度
          double allHeight = heightRow * y;   //合并单元格总高
          double allWidth = widthRow * x;  //合并单元格总宽
          /**
           * 1.把高满铺,计算宽是否超出
           * 2.不超出,计算宽占得格总数,在中间画
           * 3.超出,那么把宽满铺,计算高的格子总数,在中间画
           */
          HSSFClientAnchor anchor = null;
          double  proportion= allHeight / imageOriginalHeight;   //比例
          double estimateWidth = imageOriginalWidth * proportion;   // 高满铺时要求宽那么多
          if(estimateWidth <= allWidth){  //2.不超出,计算宽占得格总数,在中间画
              double actWidth = allHeight*(imageOriginalWidth / imageOriginalHeight);
              double actWidthCount = actWidth / widthRow;  //需要的行数
              double side = (x - actWidthCount) / 2;
              int sideInt = (int) Math.round(side);
          
              anchor = new HSSFClientAnchor(10, 10, 1000, 250,
                      (short) (cell.getColumnIndex()+sideInt), cell.getRowIndex(), //开始坐标
                      (short) ((short) cell.getColumnIndex() + x-sideInt-1), cell.getRowIndex() + y-1); // 结束坐标获取不到,只能累加
          }else {  //3.超出,那么把宽满铺,计算高的格子总数,在中间画
              double actHeight = allWidth/(imageOriginalWidth / imageOriginalHeight);
              double actHeightCount = actHeight / heightRow;  //需要的行数
              double top = (y-actHeightCount)/2;
              int topInt = (int) Math.round(top);
          
              anchor = new HSSFClientAnchor(10, 10, 1000, 250,
                      (short) (cell.getColumnIndex()), cell.getRowIndex()+topInt, //开始坐标
                      (short) ((short) cell.getColumnIndex() + x-1), cell.getRowIndex() + y-topInt-1); // 结束坐标获取不到,只能累加
          }
          
          // 插入图片
          HSSFPatriarch patriarch = sheetPicture.createDrawingPatriarch();
          patriarch.createPicture(anchor, workbook.addPicture(fileContentBmp,HSSFWorkbook.PICTURE_TYPE_JPEG));
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值