c# 使用NPOI向Excel中的应用三(插入图片 )

这是我写的一个方法:

直接调用即可:

c# 使用NPOI向Excel中的应用(创建一个excel )

c# 使用NPOI向Excel中的应用二(输出数据库中的数据 )

c# 使用NPOI向Excel中的应用(插入图片 )

 

        //excel添加图片
        private static void Picture(IWorkbook workbook, ISheet sheet, int x, int y, int xc, int yc, int sign)
        {
            DataTable strdata = GetESIDPicture(sign);
            var serverPath = System.Web.Hosting.HostingEnvironment.MapPath("/");
            string strurl = serverPath + strdata.Rows[0][0].ToString();
            //本地测试
            //FileWebRequest request = (FileWebRequest)WebRequest.Create(@"D:\program\BadmintonWebService\BadmintonWebService\SignPicture\21aad64f6-67bb-476e-8527-c89e50216915.jpg");
            //上线
            FileWebRequest request = (FileWebRequest)WebRequest.Create(strurl);
            byte[] bytes;
            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                using (MemoryStream mstream = new MemoryStream())
                {
                    int count = 0;
                    byte[] buffer = new byte[1024];
                    int readNum = 0;
                    while ((readNum = stream.Read(buffer, 0, 1024)) > 0)
                    {
                        count = count + readNum;

                        mstream.Write(buffer, 0, 1024);

                    }
                    mstream.Position = 0;
                    using (BinaryReader br = new BinaryReader(mstream))
                    {
                        bytes = br.ReadBytes(count);
                    }
                }
            }
            //第二步:将图片添加到workbook中  指定图片格式 返回图片所在workbook->Picture数组中的索引地址(从1开始)
            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
            //第三步:在sheet中创建画部
            IDrawing patriarch = sheet.CreateDrawingPatriarch();
            //第四步:设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
            IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, x, y, xc, yc);
            //第五步:创建图片
            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
        }

patriarch.CreateAnchor(0, 0, 0, 0, x, y, xc, yc); 

看下这几个参数。

操作最平凡的为后面几个参数

实例 调用:

Picture(workbook, sheet, 6, rc + 5, 7, rc + 7, addRegFillFileLog.ESID);

调用的时候下面的6、7分别是从第几列开始到第几列结束。图片占用了一列

假如rc=100 代表了105行到107行的。图片 占了两个单元格

workbook, sheet不必解释了。

可以参考一、二链接。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值