我试图将图像添加到已包含文本的单元格(XSSFSheet中的xssfcell)
anchor.setCol1(1);
anchor.setRow1(1);
anchor.setCol2(2);
anchor.setRow2(1);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
但图像会覆盖该单元格中的文本。有没有办法在单个单元格中一个接一个地添加带有文本的图像而没有多行。我也使用了autoSizeColumn()方法,但没有用完。
答案 0 :(得分:0)
在Excel
张中,图片不在单元格中,而是悬停在单元格上的图层中。它们以下列方式锚定在细胞上:
单个单元格锚点确定图片的左上角位置。如果使用,则必须将图片大小调整为其原始大小。
两个单元格锚点确定左上角位置和图片的大小。第一锚确定左上位置,而第二锚确定右下位置。所以给出了尺寸。
每个锚点都可以有一行和一列,但也可以是dx
和dy
。 dx
和dy
将添加到列和行的位置以确定最终位置。 dx
和dy
的衡量单位为EMU
。 Apache 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();
}
}
结果: