| 網(wǎng)站首頁 | 關(guān)于我們 | 開發(fā)優(yōu)勢 | 產(chǎn)品展示 |
| 合作企業(yè) | 新聞動態(tài) | 聯(lián)系我們 | 電話聯(lián)系 |
文章作者:濟南軟件開發(fā) 時間:2016年11月08日
在POI中有HSSFPatriarch對象,該對象為畫圖的頂級管理器,它的createPicture(anchor, pictureIndex)方法就能夠在Excel插入一張圖片。所以要在Excel中插入圖片,三步就可以搞定。一、獲取HSSFPatriarch對象,二、new HSSFClientAnchor對象,三、調(diào)用createPicture方法即可。實現(xiàn)倒是非常容易實現(xiàn),如果想把它做好還是有點兒難度的。這里我們先插入一張圖片:
復(fù)制代碼
public class ExcelImageTest {
public static void main(String[] args) {
FileOutputStream fileOut = null;
BufferedImage bufferImg = null;
//先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產(chǎn)生ByteArray
try {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File("F:/圖片/照片/無名氏/小昭11.jpg"));
ImageIO.write(bufferImg, "jpg", byteArrayOut);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("test picture");
//畫圖的頂級管理器,一個sheet只能獲取一個(一定要注意這點)
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
//anchor主要用于設(shè)置圖片的屬性
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8);
anchor.setAnchorType(3);
//插入圖片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
fileOut = new FileOutputStream("D:/測試Excel.xls");
// 寫入excel文件
wb.write(fileOut);
System.out.println("----Excle文件已生成------");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fileOut != null){
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
復(fù)制代碼
如下為執(zhí)行后的結(jié)果:
POI_01
至于為什么會是這樣的結(jié)果,主要是因為HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8)這個構(gòu)造函數(shù)造成的,下面我就來解釋這個構(gòu)造函數(shù):HSSFClientAnchor(int dx1,int dy1,int dx2,int dy2,short col1,int row1,short col2, int row2);各個參數(shù)的含義如下:
dx1:the x coordinate within the first cell。
dy1:the y coordinate within the first cell。
dx2:the x coordinate within the second cell。
dy2:the y coordinate within the second cell。
col1:the column (0 based) of the first cell。
row1:the row (0 based) of the first cell。
col2:the column (0 based) of the second cell。
row2:the row (0 based) of the second cell。
這里dx1、dy1定義了該圖片在開始cell的起始位置,dx2、dy2定義了在終cell的結(jié)束位置。col1、row1定義了開始cell、col2、row2定義了結(jié)束cell。
POI_02
下面是有兩個不同的構(gòu)造函數(shù)所創(chuàng)建的,從這幅圖中我們可以清晰看到上面八個參數(shù)的含義和不同之處。
POI_03
上面是插入一張圖片,那么實現(xiàn)插入多張圖片呢?其實很簡單,構(gòu)造多個不同的HSSFClientAnchor對象,控制好那八個參數(shù),如下:
HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023,100,(short) 1, 1, (short)5, 8);
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 1023,100,(short) 1, 9, (short)5, 16);
//插入圖片
patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
patriarch.createPicture(anchor2, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
想要了解更多詳情歡迎來電咨詢18678812288
登陸網(wǎng)址:m.h6244.cn。
聯(lián)系人:王經(jīng)理。