我有三张图片需要使用 Poi Apache 库插入到三张不同的工作表中,但是所有 3 张图片都插入到最后一张工作表中,请告诉我需要做什么才能将图像插入到不同的工作表中。帮助表示赞赏。-------------------------------------------------- -------------------------------------------------- -----------------
public class Img2xls {
public static byte[] bytes;
public static HSSFWorkbook my_workbook;
public static HSSFSheet my_sheet;
public static InputStream my_banner_image;
private static HSSFPatriarch drawing;
// Initializing employees data to insert into the excel file
public static void main(String[] args) throws IOException, InvalidFormatException{
String path1 = "C:\\Users\\ELCOT\\Pictures\\screen1.png";
String path2 = "C:\\Users\\ELCOT\\Pictures\\screen2.png";
String path3 = "C:\\Users\\ELCOT\\Pictures\\screen1.png";
/* Create a Workbook and Worksheet */
my_workbook = new HSSFWorkbook();
my_sheet = my_workbook.createSheet("Vista");
my_sheet = my_workbook.createSheet("Hub2");
my_sheet = my_workbook.createSheet("D42");
HSSFSheet my_sheet1 = my_sheet;
/* Create the drawing container */
drawing = my_sheet1.createDrawingPatriarch();
getImage(path1,0);
getImage(path2,40);
getImage(path3,80);
/* Write changes to the workbook */
FileOutputStream out = new FileOutputStream(new File("excel_insert_image_example.xls"));
my_workbook.write(out);
out.close();
}
public static void getImage(String img,int i) throws FileNotFoundException, IOException{
Row headerRow = my_sheet.createRow(i);
Cell cell = headerRow.createCell(0);
cell.setCellValue("Server 1");
my_sheet.autoSizeColumn(0);
/* Read the input image into InputStream */
my_banner_image = new FileInputStream(img);
/* Convert Image to byte array */
bytes = IOUtils.toByteArray(my_banner_image);
/* Add Picture to workbook and get a index for the picture */
int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
//int my_picture_id = my_workbook.addPictur
/* Close Input Stream */
my_banner_image.close();
/* Create an anchor point */
ClientAnchor my_anchor = new HSSFClientAnchor();
/* Define top left corner, and we can resize picture suitable from there */
my_anchor.setCol1(2);
my_anchor.setRow1(i);
/* Invoke createPicture and pass the anchor point and ID */
HSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
/* Call resize method, which resizes the image */
my_picture.resize();
}
}