2017-02-15 39 views
1

我使用的Apache POI 3.15其工作文件在Excel中插入圖像,但我想邊界線添加到圖像可通過完成右鍵點擊圖片 - >格式圖片 - >填充&線 - >線 - > MS Office中的實線搜索了很多關於SO和apache文檔,但沒有線索如何使用poi實現這一點。下面我的代碼圖片格式有填充和線條使用Apache POI在Java中

private void drawImageOnExcelSheetForGLOS(XSSFSheet sitePhotosSheet, 
     int row1, int row2, int col1, int col2, String fileName) { 
    try { 

     InputStream is = new FileInputStream(fileName); 
     byte[] bytes = IOUtils.toByteArray(is); 
     int pictureIdx = sitePhotosSheet.getWorkbook().addPicture(bytes,Workbook.PICTURE_TYPE_JPEG); 
     is.close(); 
     CreationHelper helper = sitePhotosSheet.getWorkbook().getCreationHelper(); 

     // Create the drawing patriarch. This is the top level container for 
     // all shapes. 
     Drawing drawing = sitePhotosSheet.createDrawingPatriarch(); 

     // add a picture shape 
     ClientAnchor anchor = helper.createClientAnchor(); 
     anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE); 


     // set top-left corner of the picture, 
     // subsequent call of Picture#resize() will operate relative to it 
     anchor.setCol1(col1); 
     anchor.setCol2(col2); 
     anchor.setRow1(row1); 
     anchor.setRow2(row2); 

     drawing.createPicture(anchor, pictureIdx); 

    } catch(Exception e) { 
    } 
} 

我能夠得出使用XSSFSimpleShape周圍畫線的,但它不是我想要的東西與setBorderXXX(準確,也嘗試過),但這些邊界或線不與圖像移動時使用MS設爲辦公室。 第一形象展示什麼,我得到和第二說明了什麼我想 enter image description here

+2

的'drawing.createPicture(錨,pictureIdx) ;'不是一個無效的方法。它返回一個[XSSFPicture](https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFPicture.html)。這擴展了[XSSFShape](https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFShape.html)並繼承了一些'setLine ...'方法。你有沒有嘗試過使用這些方法? –

回答

3

這可以通過使用XSSFPicture的setLineXXX(實現)方法如下,

private void drawImageOnExcelSheetForGLOS(XSSFSheet sitePhotosSheet, 
     int row1, int row2, int col1, int col2, String fileName) { 
    try { 

     InputStream is = new FileInputStream(fileName); 
     byte[] bytes = IOUtils.toByteArray(is); 
     int pictureIdx = sitePhotosSheet.getWorkbook().addPicture(bytes,Workbook.PICTURE_TYPE_JPEG); 
     is.close(); 
     CreationHelper helper = sitePhotosSheet.getWorkbook().getCreationHelper(); 

     XSSFDrawing drawing = sitePhotosSheet.createDrawingPatriarch(); 

     ClientAnchor anchor = helper.createClientAnchor(); 
     anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE); 

     anchor.setCol1(col1); 
     anchor.setCol2(col2); 
     anchor.setRow1(row1); 
     anchor.setRow2(row2); 

     // setLineXXX() methods can be used to set line border to image 
     XSSFPicture pic = drawing.createPicture(anchor, pictureIdx); 
     // 0 indicates solid line 
     pic.setLineStyle(0); 
     // rgb color code for black line 
     pic.setLineStyleColor(0, 0, 0); 
     // double number for line width 
     pic.setLineWidth(1.5); 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
}