心在飞扬
2021-06-28 17:37
采纳率: 33.3%
浏览 88

C# Npoi 如何往excel插入图片??

百度了一下,这个方法很简单,也很容易懂。但是为啥我操作的时候,返回的是0?

 

Bitmap tmpJPN = PagePhoto.GetWebSiteThumbnail(url, 250, 250, 250, 250);
//上面的位图没问题

MemoryStream ms111 = new MemoryStream();
tmpJPN.Save(ms111, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] buff = ms111.ToArray(); //二进制有数据

int pictureIdx = hbook.AddPicture(buff, PictureType.JPEG); //这里直接返回了0??

//这样就导致后面无法插入了


XSSFDrawing patriarch = (XSSFDrawing)a.CreateDrawingPatriarch();

 XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, maxRows + 4, 1, maxRows + 4);

 XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);

这个是为啥...引起的原因是啥? 

 

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 雨夹雪 2021-07-01 14:30
    已采纳

    你的代码没问题,加上这句pict.Resize()就可以了

      private void button2_Click(object sender, EventArgs e)
            {
                IWorkbook hbook = new XSSFWorkbook();
                ISheet a = hbook.CreateSheet("Sheet1");
                IRow excelRow = a.CreateRow(1);
    
    
    
                Bitmap tmpJPN = (Bitmap)Image.FromFile(@"D:\Desktop\微信图片_20210701133515.jpg");
                
    
                //以下是你的代码
                MemoryStream ms111 = new MemoryStream();
                tmpJPN.Save(ms111, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] buff = ms111.ToArray(); //二进制有数据
                int pictureIdx = hbook.AddPicture(buff, PictureType.JPEG); //这里没问题
    
    
                XSSFDrawing patriarch = (XSSFDrawing)a.CreateDrawingPatriarch();
                XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1,  4, 1,  4);
             
                XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
    
                pict.Resize();   //加这句就可以了
    
                //以上
    
                MemoryStream ms = new MemoryStream();
                hbook.Write(ms);
    
                byte[] data = ms.ToArray();
                FileStream fs = new FileStream(@"D:\test.xlsx", FileMode.Create);
                fs.Write(data, 0, data.Length);
                fs.Close();
    
    
                MessageBox.Show("OK");
    
            }
    
    已采纳该答案
    1 打赏 评论
  • 心在飞扬 2021-06-28 17:39

     获取的图片,均没有问题

    打赏 评论
  • 心在飞扬 2021-07-02 09:49

    可以了

    打赏 评论

相关推荐 更多相似问题