前置代码
IWorkbook wb = new XSSFWorkbook();ISheet sheet = wb.CreateSheet("Sheet1"); //创建一个名称为XX的表
1、将远程图片下载到本地,并获取本地路径地址
public static string GetImageRoute(string picUrl){try{var Folder = AppDomain.CurrentDomain.BaseDirectory + "/wwwroot/Upload/Image";if (Directory.Exists(Folder) == false)//如果不存在就创建file文件夹{Directory.CreateDirectory(Folder);}var fileName = Folder + "/" + Guid.NewGuid().ToString().Replace("-", "") + ".jpg";DownloadPicture(picUrl, fileName);return fileName;}catch (Exception ex){return "";}}/// <summary>/// 从图片地址下载图片到本地磁盘/// </summary>/// <param name="picUrl">远程url路径</param>/// <param name="savePath">本地路径</param>/// <param name="timeOut"></param>/// <returns></returns>private static bool DownloadPicture(string picUrl, string savePath, int timeOut = -1){bool value = false;WebResponse response = null;Stream stream = null;try{HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);if (timeOut != -1) request.Timeout = timeOut;response = request.GetResponse();stream = response.GetResponseStream();if (!response.ContentType.ToLower().StartsWith("text/"))value = SaveBinaryFile(response, savePath);}finally{if (stream != null) stream.Close();if (response != null) response.Close();}return value;}private static bool SaveBinaryFile(WebResponse response, string savePath){bool value = false;byte[] buffer = new byte[1024];Stream outStream = null;Stream inStream = null;try{if (File.Exists(savePath)) File.Delete(savePath);outStream = System.IO.File.Create(savePath);inStream = response.GetResponseStream();int l;do{l = inStream.Read(buffer, 0, buffer.Length);if (l > 0) outStream.Write(buffer, 0, l);} while (l > 0);value = true;}finally{if (outStream != null) outStream.Close();if (inStream != null) inStream.Close();}return value;}
// 下载图片,保存到本地,返回图片本地路径,如"C:/1.jpg"var filename = GetImageRoute("/0121/9252150_101440518391_2.jpg");
2、读取图片到byte数组
byte[] bytes = File.ReadAllBytes(filename);
3、将图片添加到workbook中 指定图片格式 返回图片所在workbook->Picture数组中的索引地址(从1开始)
int pictureIdx = wb.AddPicture(bytes, PictureType.JPEG);
4、在sheet中创建画部
XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
5、设置锚点 (在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, j, i + 1, j + 1, i + 2);// j:第几列 i:第几行
6、创建图片
XSSFPicture picture = (XSSFPicture)drawing.CreatePicture(anchor, pictureIdx);
7、删除本地图片
File.Delete(fileName);
8、代码下载
/kosmos1991/ExcelAboutPicture.git
如果觉得《导出Excel之单元格插入图片》对你有帮助,请点赞、收藏,并留下你的观点哦!