【NPOI】匯出Excel帶圖片
阿新 • • 發佈:2021-11-24
1. 本地路徑圖片
//填寫內容 for (int i = 0; i < dt.Rows.Count; i++) { IRow row = sheet.CreateRow(i + 1 + 1); row.Height = 80 * 20; //設定excel行高,畫素點是1/20 for (int j = 0; j < dt.Columns.Count; j++) { if (j == 4) { var dPath = AppDomain.CurrentDomain.BaseDirectory + dt.Rows[i][j].ToString().Replace(@"/", @"\"); if (File.Exists(dPath)) //防止檔案不存在時報錯 { byte[] picBytes = System.IO.File.ReadAllBytes(dPath); int picIndex = workbook.AddPicture(picBytes, NPOI.SS.UserModel.PictureType.JPEG); XSSFDrawing patr = (XSSFDrawing)sheet.CreateDrawingPatriarch(); XSSFClientAnchor anchor= new XSSFClientAnchor(0, 0, 0, 0, j, i + 2, j + 1, i + 3); XSSFPicture picture = (XSSFPicture)patr.CreatePicture(anchor, picIndex); } } else { row.CreateCell(j, CellType.String).SetCellValue(dt.Rows[i][j].ToString()); } } }
2. 網路路徑圖片
/// <summary> /// 向sheet插入圖片 /// </summary> private static void AddCellPicture(ISheet sheet, XSSFWorkbook workbook, string imgPath, int row, int col) { Uri uri = new Uri(imgPath); //imgPath :網路圖片地址 WebRequest webRequest = WebRequest.Create(uri); using (WebResponse webResponse = webRequest.GetResponse()) { //防止發生報錯:GDI+中發生一般性錯誤的解決辦法 Bitmap bitmap = new Bitmap(webResponse.GetResponseStream()); //讀取圖片流 Bitmap OldImage = new Bitmap(bitmap);//將圖片流複製到新的圖片流中 bitmap.Dispose(); //將原來的圖片流釋放,將圖片檔案進行解鎖。 using (MemoryStream ms = new MemoryStream()) { OldImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] bytes = ms.ToArray(); int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG); //新增圖片 XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch(); XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row + 2, col + 1, row + 3); //圖片位置,圖片左上角為(col, row) XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); //pict.Resize(); //用圖片原始大小來顯示 } } }