Java POI implementation inserts images into Excel

Source: Internet
Author: User

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 !!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.