.net 导出excel 带图片

需要引入 NPOI包 
导出excel:        
/// <summary>     /// 导出excel     /// </summary>     /// <param name="dto"></param>     /// <returns></returns>    public FileStreamResult OutPutCustomerVisits(OutPutCustomerVisitsRequest dto) { var excelName = "导出的excel模板名"; var workbook = GetWorkbookFromResourceTemplate(excelName, false); var sheet = workbook.GetSheetAt(0); var datas = new List<object>()//要插入excel中的数据 var startRowIndex = 1; if (datas.Count > 10) sheet.CopyInsertRow(startRowIndex, datas.Count - 10); for (int e = 0; e < datas.Count; e++, startRowIndex++) { var data = datas[e]; sheet.SetCellValue(startRowIndex, 0, e + 1); //序号 sheet.SetCellValue(startRowIndex, 1, data.EnterpriseName); sheet.SetCellValue(startRowIndex, 2, data.InterviewRecordType); sheet.SetCellValue(startRowIndex, 3, data.Datetime); sheet.SetCellValue(startRowIndex, 4, data.RecordPerson); sheet.SetCellValue(startRowIndex, 5, data.RecordMember); sheet.SetCellValue(startRowIndex, 6, data.Record); if (data.Imgs.IsNotNullOrWhiteSpace()) AddPieChart(sheet, workbook, data.Imgs, startRowIndex, 7);//图片 } return ToFileResult(workbook, $"{excelName}.xlsx", dto.Password); } /// <summary> /// 添加图片到excel中 /// </summary> /// <param name="sheet"></param> /// <param name="workbook"></param> /// <param name="fileurl"></param> /// <param name="row"></param> /// <param name="col"></param> private void AddPieChart(ISheet sheet, IWorkbook workbook, string fileurl, int row, int col) { try {var res = ;//查服务器上或本地图片 byte[] bytes = Convert.FromBase64String(res.Data.ToString());//将图片转为byte[] if (!string.IsNullOrEmpty(fileurl)) { //类型 PictureType type = PictureType.JPEG; if (fileurl.IndexOf(".png") > -1) type = PictureType.PNG; else if (fileurl.IndexOf(".bmp") > -1) type = PictureType.BMP; int pictureIdx = workbook.AddPicture(bytes, type); // 创建绘图对象并设置图片位置和大小 IDrawing patriarch = sheet.CreateDrawingPatriarch(); IClientAnchor anchor = workbook.GetCreationHelper().CreateClientAnchor(); /* * dx1 dy1 起始单元格中的x,y坐标. * dx2 dy2 结束单元格中的x,y坐标 * col1,row1 指定起始的单元格,下标从0开始 * col2,row2 指定结束的单元格 ,下标从0开始 */ anchor.Col1 = col; // 图片所在列的起始位置 anchor.Row1 = row; // 图片所在行的起始位置 anchor.Col2 = col + 1; anchor.Row2 = row + 1; anchor.Dx1 = 0; anchor.Dy1 = 0; anchor.Dx2 = 10; anchor.Dy2 = 30; // 插入图片 IPicture picture = patriarch.CreatePicture(anchor, pictureIdx); } } catch (Exception ex) { } } /// <summary> /// 从资源模板中加载工作薄 /// </summary> /// <param name="resourceName">资源名称</param> /// <returns></returns> private IWorkbook GetWorkbookFromResourceTemplate(string resourceName) {   using (Stream stream = new MemoryStream((byte[])Resource.ResourceManager.GetObject(resourceName, Resource.Culture)))   {     return stream.GetWorkbook();   } }

//导入excel

public ResponseWrapper ImportCustomerVisits([FromForm] ImportFileDto dto)
{
 if (dto == null) throw new FriendlyException("请求参数不能为空.");

            IWorkbook workbook = dto.File.OpenReadStream().GetWorkbook();
            ISheet sheet = workbook.GetSheetAt(0);
       var table = sheet.ToDataTable();
for (int index = 0; index < table.Rows.Count; index++)
            {
                var row = table.Rows[index];

                var name = row.GetRowCellValue("xx");

                // 读取文件中的图片
                var image = ImgList.Where(img => img.ClientAnchor.Row1 == index + 1)?.First();
                var imgStr = "";
                if (image != null)
                {
                    byte[] pictureData = image.PictureData.Data;
                    //图片类型
                    var imgType = image.PictureData.PictureType;

                    var imgName = Guid.NewGuid() + "";
                    if (imgType == PictureType.PNG) imgName += ".png";
                    else if (imgType == PictureType.JPEG) imgName += ".jpeg";
                    else if (imgType == PictureType.BMP) imgName += ".bmp";

                    imgStr = UploadImageToBase64(pictureData, imgName);
                }


                _xxxRepository.InsertAsync(new xxxModel
                {
    
                });
            }

            _xxxRepository.SaveChanges();

}    

/// <summary>
        /// 将excel中的图片上传到服务器
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="fileName">图片名,必须加后缀</param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private string UploadImageToBase64(byte[] bytes, string fileName, string scope = "")
        {var res = xxx;//上传图片操作return imgUrl;//服务器图片地址
        }

 

 

 

posted on 2023-09-18 18:03  可乐冒泡泡丶  阅读(200)  评论(0编辑  收藏  举报