天天看點

Java Excel 插入圖檔

   在POI中有HSSFPatriarch對象,該對象為畫圖的頂級管理器,它的createPicture(anchor, pictureIndex)方法就能夠在Excel插入一張圖檔。是以要在Excel中插入圖檔,三步就可以搞定。

  一、擷取HSSFPatriarch對象,

  二、new HSSFClientAnchor對象,

  三、調用createPicture方法即可。

  實作倒是非常容易實作,如果想把它做好還是有點兒難度的。這裡我們先插入一張圖檔:

如下為執行後的結果:

Java Excel 插入圖檔

      至于為什麼會是這樣的結果,主要是因為HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8)這個構造函數造成的,下面我就來解釋這個構造函數:HSSFClientAnchor(int dx1,int dy1,int dx2,int dy2,short col1,int row1,short col2, int row2);各個參數的含義如下:

      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的結束位置。col1、row1定義了開始cell、col2、row2定義了結束cell。

Java Excel 插入圖檔

      下面是有兩個不同的構造函數所建立的,從這幅圖中我們可以清晰看到上面八個參數的含義和不同之處。

Java Excel 插入圖檔

      上面是插入一張圖檔,那麼實作插入多張圖檔呢?其實很簡單,構造多個不同的HSSFClientAnchor對象,控制好那八個參數,如下:

      其餘代碼一樣,得到如下結果:

Java Excel 插入圖檔