For Web development, you must deal with Excel. Today, the boss gave me a task-export Excel. At first, I thought it was quite simple. I just wanted to search, build an Excel file, and download response. However, the difference is that you want to add images. It takes a long time to add images. At the same time, no good information was found on the network. Therefore, I wrote this blog record for you and bloggers to query and reference.
There is an HSSFPatriarch object in POI, which is the top-level manager of the drawing. Its createPicture (anchor, pictureIndex) method can insert an image in Excel. Therefore, you can insert an image in Excel in three steps. 1. Get the HSSFPatriarch object. 2. new HSSFClientAnchor object. 3. Call the createPicture method. Implementation is very easy to implement. It is still a little difficult to do it well. Here we insert an image first:
= BufferedImage bufferImg = ImageIO. read (File ("F:/picture/Photo/Anonymous/Xiao Zhao 11.jpg" ImageIO. write (bufferImg, "jpg"HSSFWorkbook wb </span> = <span patriarch. createPicture (anchor, wb. addPicture (byteArrayOut. toByteArray (), HSSFWorkbook. PICTURETYPEJPEG); fileOut = FileOutputStream ("D:/test excel.xls" System. out. println ("---- Excle file generated ------" (fileOut! =
The execution result is as follows:
HSSFClientAnchor(0, 0, 1023,100,() 1, 1, ()5, 8= HSSFClientAnchor(0, 0, 1023,100,() 1, 9, ()5, 16
The following results are obtained for the rest of the Code:
In the next article, I will provide a general template generated in Excel that supports custom styles, titles, and image writing !!