我使用的图片.调整大小,不工作
如果图片尺寸很大,我希望图片适合Excel单元格如果图片很大,它将根据单元格调整大小,我想要一个矩形单元格
这里是excel工作表的图片在这里输入图片描述
这是我写的代码,我在两列三行中输入数据,我使其静态,但数据将动态出现
public静态void main(String[]args)抛出IOException{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("My Sheet2");
Cell cell1 = sheet.createRow(0).createCell(0);
Cell cell2 = sheet.createRow(1).createCell(0);
cell1.setCellValue("this is Image1");
cell2.setCellValue("this is Image2");
InputStream inputStream1 = new FileInputStream("src/main/resources/Image1.png");
InputStream inputStream2 = new FileInputStream("src/main/resources/Image2.png");
byte[] inputImage1 = IOUtils.toByteArray(inputStream1);
byte[] inputImage2 = IOUtils.toByteArray(inputStream2);
int inputImagePicture1 = workbook.addPicture(inputImage1 , Workbook.PICTURE_TYPE_PNG);
int inputImagePicture2 = workbook.addPicture(inputImage2 , Workbook.PICTURE_TYPE_PNG);
inputStream1.close();
inputStream2.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor forImage1 = helper.createClientAnchor();
ClientAnchor forImage2 = helper.createClientAnchor();
forImage1.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
forImage2.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
forImage1.setCol1(1);
forImage1.setCol2(2);
forImage1.setRow1(0);
forImage1.setRow2(1);
forImage2.setCol1(1);
forImage2.setCol2(2);
forImage2.setRow1(1);
forImage2.setRow2(2);
drawing.createPicture(forImage1 , inputImagePicture1);
drawing.createPicture(forImage2 , inputImagePicture2);
int widthUnit = 25*256;
sheet.setColumnWidth(1,widthUnit);
short heightUnit = 60*20;
cell1.getRow().setHeight(heightUnit);
cell2.getRow().setHeight(heightUnit);
for(int i=0; i<3; i++){
sheet.autoSizeColumn(i);
}
try(FileOutputStream saveExcel = new FileOutputStream("target/newWorkbook.xls")) {
workbook.write(saveExcel);
}
}
试试这个
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
CreationHelper helper = workbook.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(colStart); //Col Start
anchor.setRow1(rowStart); //Row Start
anchor.setCol2(colEnd); //Col End
anchor.setRow2(rowEnd); //Row End
//create a picture anchored to Top-Left Corner
Drawing drawing = sheet.createDrawingPatriarch();
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize(1);