Apache POI写图像和文本excel

时间:2017-11-27 03:17:30

标签: java excel apache-poi

我在同一个单元格中编写图像和文本时遇到问题,并且问题类似于StackOverflow on addding image and text in same cell in excelPOI Excel HSSFPicture Image and ALT TEXT ,但预期的输出是不同的,我无法弄清楚我的代码有什么问题? 和预期的输出如下

enter image description here

这是我的代码;

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            //FileInputStream obtains input bytes from the image file
            InputStream inputStream = new FileInputStream(k_pipe_img_file);
            //Get the contents of an InputStream as a byte[].
            byte[] bytes = IOUtils.toByteArray(inputStream);
            //Adds a picture to the workbook
            int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
            //close the input stream
            inputStream.close();

            //Returns an object that handles instantiating concrete classes
            CreationHelper helper = workbook.getCreationHelper();

            //Creates the top-level drawing patriarch.
            Drawing drawing = sheet.createDrawingPatriarch();

            ClientAnchor anchor1 = new XSSFClientAnchor();
            anchor1.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);

            anchor1.setCol1(1);
            anchor1.setCol2(1);
            anchor1.setRow1(2);
            anchor1.setRow2(2);

            //Creates a picture
            Picture pict = drawing.createPicture(anchor1, pictureIdx);
            pict.resize(1, 1);

            Row row = sheet.createRow(2);
            row.setHeight((short) 4000);

            sheet.setColumnWidth(0, 4000);
            Cell cell = row.createCell(0, CellType.STRING);
            cell.setCellValue("Task 1");

            sheet.setColumnWidth(1, 5000);
            cell = row.createCell(1, CellType.STRING);
            cell.setCellValue("Replace Kemplon-Pipe");
            CellStyle style=row.getSheet().getWorkbook().createCellStyle();
            style.setVerticalAlignment(VerticalAlignment.TOP);
            cell.setCellStyle(style);

            //Write the Excel file
            FileOutputStream fileOut = new FileOutputStream(k_Task_file);
            workbook.write(fileOut);
            fileOut.close();

代码输出: enter image description here

图像占据整个单元格,文本位于图像后面。

有没有可能的解决方案?

1 个答案:

答案 0 :(得分:6)

Excel张中,图片不在单元格中,而是悬停在单元格上的图层中。它们以下列方式锚定在细胞上:

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

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

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

其中一个问题是apache poi有一个方法来获取像素的宽度,而它只有一个方法来获得点的行高。因此,我们需要考虑两种不同的测量单位。

另一个问题是,如果我们想要尊重图片的宽高比,那么我们首先需要确定图片文件的原生大小。如何在Java中获取jpg文件的原生大小有很多问题/答案。所有的答案都非常复杂,我认为没有一个真的很好。

以下示例将图片定位在距离左边单元格边界20 px的单元格B3上,距离顶部单元格边界20pt,从右边单元格边框到宽度最多20px,从底部单元格边框到高度10pt。

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 ExcelDrawImagesOverCell {

 private static void drawImageOnExcelSheet(XSSFSheet sheet, int row, int col, 
  int left/*in px*/, int top/*in pt*/, int width/*in px*/, int height/*in pt*/, 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.setDx1(Units.pixelToEMU(left)); //dx = left in px
  anchor.setDy1(Units.toEMU(top)); //dy = top in pt

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

  drawing.createPicture(anchor, pictureIdx);

 }

 public static void main(String[] args) throws Exception {

  Workbook wb = new XSSFWorkbook();

  CellStyle styleVertAlingTop = wb.createCellStyle();
  styleVertAlingTop.setVerticalAlignment(VerticalAlignment.TOP);

  Sheet sheet = wb.createSheet();
  sheet.setColumnWidth(0, 15 * 256); //15 default characters width
  sheet.setColumnWidth(1, 30 * 256); //30 default characters width

  Row row = sheet.createRow(2);
  row.setHeight((short)(100 * 20)); //100pt height * 20 = twips (twentieth of an inch point)

  Cell cell = row.createCell(0);
  cell.setCellValue("Task 1");

  cell = row.createCell(1);
  cell.setCellValue("Replace Kemplon-Pipe");
  cell.setCellStyle(styleVertAlingTop);

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

  int left = 20; // 20px
  int top = 20; // 20pt
  int width = Math.round(sheet.getColumnWidthInPixels(1) - left - left); //width in px
  int height = Math.round(row.getHeightInPoints() - top - 10/*pt*/); //height in pt

  drawImageOnExcelSheet((XSSFSheet)sheet, 2, 1, left, top, width, height, pictureIdx);

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

结果:

enter image description here