一、NPOI Excel插入圖片案例
//創建工作簿 HSSFWorkbook wk = new HSSFWorkbook(); ISheet sheet = wk.CreateSheet("sheet1"); //sheet.SetColumnWidth(0, 1); //sheet.AutoSizeColumn(0); //添加內容 IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); HSSFRichTextString rich = new HSSFRichTextString("簽名:"); cell.SetCellValue(rich); //添加圖片 byte[] bytes = System.IO.File.ReadAllBytes(@"D:\1.jpg"); int pictureIdx = wk.AddPicture(bytes, PictureType.JPEG); HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); //HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 0, 0, 0, 1, 3); HSSFClientAnchor anchor = new HSSFClientAnchor(223, 0, 0, 0, 0, 0, 1, 1); //設置圖片變換類型 anchor.AnchorType = AnchorType.MoveDontResize; HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); //pict.Resize(100,50); //保存到文件 using (FileStream fs = File.OpenWrite("testimg.xls")) { wk.Write(fs); Console.WriteLine("導出數據成功!"); }
二、HSSFClientAnchor 位置說明
//設置圖片座標與大小 //函數原型:XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2); //座標(col1,row1)表示圖片左上角所在單元格的位置,均從0開始,比如(5,2)表示(第六列,第三行),即F3;注意:圖片左上角座標與(col1,row1)單元格左上角座標重合 //座標(col2,row2)表示圖片右下角所在單元格的位置,均從0開始,比如(10,3)表示(第十一列,第四行),即K4;注意:圖片右下角座標與(col2,row2)單元格左上角座標重合 //座標(dx1,dy1)表示圖片左上角在單元格(col1,row1)基礎上的偏移量(往右下方偏移);(dx1,dy1)的最大值爲(1023, 255),爲一個單元格的大小 //座標(dx2,dy2)表示圖片右下角在單元格(col2,row2)基礎上的偏移量(往右下方偏移);(dx2,dy2)的最大值爲(1023, 255),爲一個單元格的大小
//注意:目前測試發現,對於.xlsx後綴的Excel文件,偏移量設置(dx1,dy1)(dx2,dy2)無效;只會對.xls生效
三、繪製圖形
//繪製圖形 HSSFSimpleShape triangle = (HSSFSimpleShape)patriarch.CreateSimpleShape(anchor); triangle.ShapeType = HSSFSimpleShape.OBJECT_TYPE_PICTURE; triangle.SetFillColor(255,0,0);
四、讀取Excel模版,插入圖片
using (FileStream fs = File.OpenRead("2.xls")) { //讀取Excel HSSFWorkbook wk = new HSSFWorkbook(fs); ISheet sheet = wk.GetSheetAt(0); ICell cell = wk.GetSheetAt(0).GetRow(0).GetCell(0); //插入圖片 byte[] bytes = System.IO.File.ReadAllBytes(@"D:\1.jpg"); int pictureIdx = wk.AddPicture(bytes, PictureType.JPEG); HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); HSSFClientAnchor anchor = new HSSFClientAnchor(223, 0, 0, 0, 0, 0, 1, 1); anchor.AnchorType = AnchorType.MoveDontResize; HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); //保存 using (FileStream fsNew = File.OpenWrite("testimg2.xls")) { wk.Write(fsNew); Console.WriteLine("導出數據成功!"); } }
更多:
NPOI Excel導出報錯 Cannot access a closed stream
NPOI Excel導出超出65536行報錯 Invalid row number (65536) outside allowable range (0..65535)解決方法