先看下效果:
效果:
在三行两列分别插入文字和图片:第一列纯文本,第二列是对应的图片。
下面上代码:
/**
* This Method loads the image from application resource and insert into the
* Cell
*/
private static void insertImageToCell(Workbook workbook, String fileType, int rowNum, Drawing drawing,
String imageName) throws IOException {
//Loading image from application resource
InputStream is = new FileInputStream(imageName); //ReportBase.class.getClassLoader().getResourceAsStream(imageName);
//Converting input stream into byte array
byte[] inputImageBytes = IOUtils.toByteArray(is);
int inputImagePictureID = workbook.addPicture(inputImageBytes, Workbook.PICTURE_TYPE_PNG);
is.close();
ClientAnchor anchor = null;
//Creating the client anchor based on file format
if (fileType.equals("xls")) {
anchor = new HSSFClientAnchor();
} else {
anchor = new XSSFClientAnchor();
}
anchor.setCol1(1);
anchor.setCol2(2);
anchor.setRow1(rowNum - 1);
anchor.setRow2(rowNum);
drawing.createPicture(anchor, inputImagePictureID);
}
private static void testExcel(){
Workbook workbook = null;
FileOutputStream fos = null;
try {
File file = new File("E:/company-logo.xlsx");
String fileType = null;
// Creating workbook object based on excel file format
if (file.getName().endsWith(".xls")) {
workbook = new HSSFWorkbook();
fileType = "xls";
} else if (file.getName().endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
fileType = "xlsx";
} else {
System.err.println("File format should be XLS or XLSX only.");
return;
}
Sheet sheet =workbook.createSheet("Company Logo");
// Creating drawing object
Drawing drawing = sheet.createDrawingPatriarch();
//Adding first row data
Row row1 = sheet.createRow(0);
row1.setHeight((short) 1000);
row1.createCell(0).setCellValue("Apple");
insertImageToCell(workbook, fileType, 1, drawing, "E:\\Pictures\\88888.png");
//Adding second row data
Row row2 = sheet.createRow(1);
row2.setHeight((short) 1000);
row2.createCell(0).setCellValue("Google");
insertImageToCell(workbook, fileType, 2, drawing, "E:\\Pictures\\88888.png");
//Adding third row data
Row row3 = sheet.createRow(2);
row3.setHeight((short) 1000);
row3.createCell(0).setCellValue("Facebook");
insertImageToCell(workbook, fileType, 3, drawing, "E:\\Pictures\\88888.png");
// Resize all columns to fit the content size
for (int i = 0; i < 3; i++) {
sheet.autoSizeColumn(i);
}
// Write the workbook to the excel file
fos = new FileOutputStream(file);
workbook.write(fos);
System.out.println("Images have been added successfully.");
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}