使用 ApachePOI 将图像定位在单元格的中间

Positioning an Image in the middle of a cell using ApachePOI

提问人:kajoe14 提问时间:10/13/2023 更新时间:10/13/2023 访问量:46

问:

我正在尝试将图像定位到 Scala 应用程序中 Excel 工作表中单元格的中间。我正在使用ApachePOI版本。但是,我的逻辑仅将图像呈现到单元格的左上角。5.0.0

如何将图像放置在给定单元格的中间。 这是我的代码逻辑:

  def addImageToCell(imagePath: String, sheet: XSSFSheet, columnIdx: Int, rowNum: Int): Unit = {
    val fis = Files.newInputStream(Path.of(imagePath))

    val pictureBytes = IOUtils.toByteArray(fis)
    val pictureIdx   = sheet.getWorkbook.addPicture(pictureBytes, Workbook.PICTURE_TYPE_PNG)
    fis.close()

    val helper  = sheet.getWorkbook.getCreationHelper
    val drawing = sheet.createDrawingPatriarch()

    val anchor = helper.createClientAnchor
    anchor.setCol1(columnIdx)
    anchor.setRow1(rowNum)

    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE)

    // load image and get its dimensions
    val bufferedImg       = ImageIO.read(new File(imagePath))
    val originalDimension = new Dimension(bufferedImg.getWidth, bufferedImg.getHeight)

    // get the cell's width & height in pixels
    val colWidthInPixels  = Math.round(sheet.getColumnWidthInPixels(columnIdx))
    val rowHeightInPixels = Math.round(sheet.getRow(rowNum).getHeightInPoints / 72 * 96)

    // calculate scale factor
    val scaleX = colWidthInPixels.toDouble / originalDimension.width
    val scaleY = rowHeightInPixels.toDouble / originalDimension.height

    // use the smaller scale factor to ensure the image fits within the cell
    val scale = Math.min(scaleX, scaleY)
    // makes certain that the scale factor cannot be below "0.1" - else the images will be too tiny
    val revisedScale = Math.max(scale, 0.1)

    // resize image
    val picture: Picture = drawing.createPicture(anchor, pictureIdx)
    picture.resize(revisedScale)

    // calculate the scaled image's new height & width
    val scaledWidth  = (originalDimension.width * revisedScale).toInt
    val scaledHeight = (originalDimension.height * revisedScale).toInt

    // calculate how much to move the image by in order to center it in the cell
    val moveX = (colWidthInPixels - scaledWidth) / 2
    val moveY = (rowHeightInPixels - scaledHeight) / 2

    // move the image to be centered in the cell
    anchor.setDx1(moveX)
    anchor.setDy1(moveY)
  }

任何帮助将不胜感激。

Java Excel Scala Apache-poi XSSF

评论

0赞 Axel Richter 10/16/2023
ClientAnchor.setDx1 指出“注意 - XSSF 和 HSSF 的坐标系略有不同,XSSF 中的值大 Units.EMU_PER_PIXEL 倍”。那么,如果你这样做会发生什么?moveX = (colWidthInPixels - scaledWidth) / 2 * Units.EMU_PER_PIXEL
0赞 kajoe14 10/16/2023
@AxelRichter - 这似乎使图像在 x 轴上移动。这真的很棒。谢谢。

答: 暂无答案