使用poi在excel中的同一单元格中添加图像和文本然后图像覆盖文本

问题描述 投票:0回答:1

Screen shot present here我试图将图像添加到单元格(在XSSFSheet中是xssfcell),它已经包含了一个文本

 anchor.setCol1(1);
     anchor.setRow1(1); 
     anchor.setCol2(2); 
     anchor.setRow2(1); 
     Picture pict = drawing.createPicture(anchor, pictureIdx);
     pict.resize();

但图像会覆盖该单元格中的文本。有没有办法在单个单元格中一个接一个地添加带有文本的图像而没有多行。我也使用了autoSizeColumn()方法,但没有解决。

java excel apache-poi
1个回答
0
投票

Excel中,图片不在细胞中,而是在细胞上的一层中盘旋。它们以下列方式锚定在细胞上:

一个单元格锚点确定图片的左上角位置。如果使用,则必须将图片大小调整为其原始大小。

双单元锚点确定左上角位置和图片大小。第一锚确定左上位置,而第二锚确定右下位置。所以给出了尺寸。

每个锚可以有一行和一列,但也有dxdydxdy将被添加到列和行的位置以确定最终位置。 dxdy的测量单位是EMUApache poi提供org.apache.poi.util.Units来计算像素中的EMU

例:

import java.io.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;

public class ExcelDrawImagesOnCellLeft {

 private static void drawImageOnExcelSheet(XSSFSheet sheet, int row, int col, 
  int height, int width, int pictureIdx) throws Exception {

  CreationHelper helper = sheet.getWorkbook().getCreationHelper();

  Drawing drawing = sheet.createDrawingPatriarch();

  ClientAnchor anchor = helper.createClientAnchor();
  anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);

  anchor.setCol1(col); //first anchor determines upper left position
  anchor.setRow1(row);

  anchor.setRow2(row); //second anchor determines bottom right position
  anchor.setCol2(col);
  anchor.setDx2(Units.toEMU(width)); //dx = left + wanted width
  anchor.setDy2(Units.toEMU(height)); //dy= top + wanted height

  drawing.createPicture(anchor, pictureIdx);

 }

 public static void main(String[] args) throws Exception {
  Workbook wb = new XSSFWorkbook();
  Sheet sheet = wb.createSheet();

  InputStream is = new FileInputStream("samplePict.jpeg");
  byte[] bytes = IOUtils.toByteArray(is);
  int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
  is.close();

  String gap = "      ";

  for (int r = 0; r < 10; r++ ) {
   sheet.createRow(r).createCell(1).setCellValue(gap + "Picture " + (r+1));
   drawImageOnExcelSheet((XSSFSheet)sheet, r, 1, 12, 12, pictureIdx);
  }

  sheet.autoSizeColumn(1);

  wb.write(new FileOutputStream("ExcelDrawImagesOnCellLeft.xlsx"));
  wb.close();
 }
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.