好吧,我修改了我的代码以消除其他因素:
package com.shangzhu.drt;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by lixiaoming on 2017/6/26.
*/
public class ImageTest2 {
private static void insertImageWithPOI() throws Exception {
XSSFWorkbook wwb = new XSSFWorkbook();
XSSFSheet ws = wwb.createSheet("sheet0");
BufferedImage image = ImageIO.read(new File("D:/poi.png"));
ByteArrayOutputStream baps = new ByteArrayOutputStream();
ImageIO.write(image,"png",baps);
int pictureIdx = wwb.addPicture(baps.toByteArray(), Workbook.PICTURE_TYPE_PNG);
XSSFDrawing drawing = ws.createDrawingPatriarch();
XSSFCreationHelper helper = wwb.getCreationHelper();
XSSFClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(1);
Picture picture = drawing.createPicture(anchor, pictureIdx);
picture.resize();
File excelFile = new File("D:/POI.xlsx");
OutputStream ops = new FileOutputStream(excelFile);
wwb.write(ops);
}
public static void main(String[] args) {
try {
insertImageWithPOI();
} catch (Exception e) {
e.printStackTrace();
}
}
}
下面是代码中的图片(" D:/poi.png"): D:/poi.png
我不认为处理图片的源代码有问题,但我不知道我错过了什么
答案 0 :(得分:2)
我确认使用默认列大小时出现问题。 XSSFPicture.resize
需要计算列宽(以像素为单位)才能获得XSSFClientAnchor
Col2
和Dx2
。只要使用默认列大小,则此计算似乎是错误的。
解决方法可能是在使用XSSFPicture.resize
之前定义显式列大小。然后以像素为单位计算列宽似乎是正确的。
在您的代码中:
...
Picture picture = drawing.createPicture(anchor, pictureIdx);
for (int c=0; c<20; c++) ws.setColumnWidth(c, 11*256);
picture.resize();
...