poi將圖片導入excel(Java代碼)


package com.fh.util;
import java.awt.image.BufferedImage;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
 
import javax.imageio.ImageIO;  
 
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;  
import org.apache.poi.hssf.usermodel.HSSFPatriarch;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
public class AAAA {

    public static void main(String[] args) {
             FileOutputStream fileOut = null;  
            BufferedImage bufferImg = null;//圖片
            try {  
                // 先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray  
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();  
                //將圖片讀到BufferedImage  
                bufferImg = ImageIO.read(new File("C:/Users/uctimes/Desktop/1.jpg"));  
                // 將圖片寫入流中  
                ImageIO.write(bufferImg, "png", byteArrayOut);  
                // 創建一個工作薄  
                HSSFWorkbook wb = new HSSFWorkbook();  
                //創建一個sheet  
                HSSFSheet sheet = wb.createSheet("out put excel");  
                // 利用HSSFPatriarch將圖片寫入EXCEL  
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
                /**
                 * 該構造函數有8個參數
                 * 前四個參數是控制圖片在單元格的位置,分別是圖片距離單元格left,top,right,bottom的像素距離
                 * 后四個參數,前連個表示圖片左上角所在的cellNum和 rowNum,后天個參數對應的表示圖片右下角所在的cellNum和 rowNum,
                 * excel中的cellNum和rowNum的index都是從0開始的
                 *  
                 */  
                //圖片一導出到單元格B2中  
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,  
                        (short) 10, 1, (short) 11, 2);  
                // 插入圖片  
                patriarch.createPicture(anchor, wb.addPicture(byteArrayOut  
                        .toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));  
                //生成的excel文件地址
                fileOut = new FileOutputStream("C:/Users/uctimes/Downloads/123.xls");  
                // 寫入excel文件  
                wb.write(fileOut);  
            } catch (IOException io) {  
                io.printStackTrace();  
                System.out.println("io erorr : " + io.getMessage());  
            } finally {  
                if (fileOut != null) {  
                    try {  
                        fileOut.close();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
    }
}

 

效果圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM