Winforn中通過NPOI匯出Excel時通過XSSFClientAnchor和XSSFPicture新增圖片
阿新 • • 發佈:2020-05-29
場景
Winform中通過NPOI匯出Excel的三種方式(HSSFWorkbook,XSSFWorkbook,SXSSFWorkbook)附程式碼下載:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106423452
在上面介紹了NPOI的三種匯出Excel的方式後,如果想在匯出的Excel中新增照片,該怎樣實現。
注:
部落格主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。
實現
通過上面的部落格添加了NPOI的引用後,拖拽一個按鈕,在按鈕的點選事件中
private void button1_Click(object sender,EventArgs e) { //新建XSSFWorkbook物件 XSSFWorkbook wb = new XSSFWorkbook(); #region 設定樣式 ICellStyle style1 = wb.CreateCellStyle();//樣式 IFont font1 = wb.CreateFont();//字型 font1.FontName = "宋體"; font1.FontHeightInPoints = 11; font1.Boldweight = (short)FontBoldWeight.Bold; style1.SetFont(font1);//樣式裡的字型設定具體的字型樣式 #endregion #region 基礎資訊頁sheet ISheet sheet0 = wb.CreateSheet("圖形"); //獲取影象 System.Drawing.Image image = Properties.Resources.badao; Byte[] bytes= ImageToBytes(image); int widthPx = image.Width; int heightPx = image.Height; int pictureIdx = wb.AddPicture(bytes,PictureType.JPEG); XSSFDrawing patriarch = (XSSFDrawing)sheet0.CreateDrawingPatriarch(); // 插圖片的位置 HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2) XSSFClientAnchor anchor = new XSSFClientAnchor(0,0,3,1,4); //把圖片插到相應的位置 XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor,pictureIdx); //設定列寬度,根據公式:POI中的列寬 ≈ 畫素/8*256 decimal width = Math.Round((decimal)(heightPx) / 8,2); //將圖片縮小為原來的十分之九 decimal lessWidth = Math.Round(width * 9 / 10,2); sheet0.SetColumnWidth(0,Decimal.ToInt32(lessWidth * 256)); IRow row3 = sheet0.CreateRow(3); //設定行高度,根據公式:POI中的行高 = 畫素/DPI*72*20 decimal poiHeight = Math.Round((decimal)(widthPx) / dpi,2); //將圖片縮小為原來的十分之九 decimal lessPoiHeight = Math.Round(poiHeight * 9 / 10,2); row3.Height = (short)Decimal.ToInt32(lessPoiHeight * 72 * 20); #endregion try { //將記憶體中的資料寫入磁碟 using (FileStream filestream = new FileStream(System.IO.Path.Combine(@"D:\","badao.xlsx"),FileMode.Create)) { wb.Write(filestream); filestream.Close(); } } catch (Exception ex) { Console.Write(ex); } }
其中用到了將image轉為byte陣列的方法
public byte[] ImageToBytes(Image image) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { image.Save(ms,ImageFormat.Bmp); byte[] buffer = new byte[ms.Length]; //Image.Save()會改變MemoryStream的Position,需要重新Seek到Begin ms.Seek(0,SeekOrigin.Begin); ms.Read(buffer,0,buffer.Length); return buffer; } }
用到的圖片的資原始檔在Resouce中新增的
執行專案,然後點選按鈕,就會在D盤下生成Excel