--------------------- 本文来自 天水宇 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xxs77ch/article/details/50553857?utm_source=copy
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Threading.Tasks;
-
using NPOI.HSSF.UserModel;
-
using NPOI.SS.Formula.Eval;
-
using NPOI.SS.Formula.Functions;
-
using NPOI.SS.UserModel;
-
using NPOI.XSSF.UserModel;
-
using NPOI.POIFS.FileSystem;
-
using NPOI.HPSF;
-
using System.IO;
-
using NPOI.SS.Util;
-
using System.Drawing;
-
using NPOI.HSSF.Util;
-
using System.Web;
-
using System.Net;
-
using System.Net.Mail;
-
namespace NPOI
-
{
-
class Program10
-
{
-
static void Main(string[] args)
-
{
-
-
//说明:插入图片
-
-
//1.创建EXCEL中的Workbook
-
IWorkbook myworkbook = new HSSFWorkbook();
-
-
//2.创建Workbook中的Sheet
-
ISheet mysheet = myworkbook.CreateSheet("sheet1");
-
-
//第一步:读取图片到byte数组
-
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://img1.soufunimg.com/message/images/card/tuanproj/201511/2015112703584458_s.jpg");
-
-
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 = myworkbook.AddPicture(bytes, PictureType.JPEG);
-
-
//第三步:在sheet中创建画部
-
IDrawing patriarch = mysheet.CreateDrawingPatriarch();
-
-
//第四步:设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
-
IClientAnchor anchor =patriarch.CreateAnchor(0,0,0,0,0,0,2,2);
-
-
-
//第五步:创建图片
-
IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
-
-
//6.保存
-
FileStream file = new FileStream(@"E:\myworkbook11.xls", FileMode.Create);
-
myworkbook.Write(file);
-
file.Close();
-
}
-
}
-
}
1 // 插入 PNG 图片至 Excel 2 String fileName = strAppRootPath + "images/" + "bxlogo.png"; 3 4 InputStream is = new FileInputStream(fileName); 5 byte[] bytes = IOUtils.toByteArray(is); 6 7 int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); 8 9 CreationHelper helper = workbook.getCreationHelper(); 10 Drawing drawing = sheet.createDrawingPatriarch(); 11 ClientAnchor anchor = helper.createClientAnchor(); 12 13 // 图片插入坐标 14 anchor.setCol1(0); 15 anchor.setRow1(1); 16 // 插入图片 17 Picture pict = drawing.createPicture(anchor, pictureIdx); 18 pict.resize();