入參:工作簿物件,某個單元格物件,將要寫入的圖片位元組陣列
物件解釋:
XSSFClientAnchor:可設定圖片放置的開始、結束單元格,X、Y 起始點位(這裡挖個坑,具體設定多少可以根據行高等進行計算,具體可參考 pic.Resize() 的實現 )
1 /// <summary> 2 /// 將圖片新增到工作簿 3 /// </summary> 4 /// <param name="workbook"></param> 5 /// <param name="cell"></param> 6 /// <param name="bytes"></param> 7 void SetCellPhoto(IWorkbook workbook, NPOI.SS.UserModel.ICell cell, byte[] bytes) 8 { 9 int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.PNG); 10 11 // 建立繪圖物件 12 var drawing = workbook.GetSheetAt(0).CreateDrawingPatriarch(); 13 14 XSSFClientAnchor anchor = new XSSFClientAnchor( 15 0, 50000, 0, 0, // 從單元格左上角開始 16 cell.ColumnIndex + 2, 17 cell.RowIndex, 18 cell.ColumnIndex + 5, 19 cell.RowIndex + 1 20 ); 21 anchor.AnchorType = (AnchorType)2; // 絕對定位 22 23 // 建立圖片物件 24 XSSFPicture pic = (XSSFPicture)drawing.CreatePicture(anchor, pictureIdx); 25 26 // 設定圖片的縮放大小 27 pic.Resize(1, 0.9); 28 }