一、NPOI导出Excel(list导出)

下载NPOI管理包

引入命名空间

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

控制器

1.先查询list集合

//string filePath = Path.Combine(_webHostEnvironment.WebRootPath + @"\excel\");物理路径
//string filePath = Path.Combine(_webHostEnvironment.ContentRootPath + @"\excel\");绝对路径
      string webRootPath = Path.Combine(_webHostEnvironment.WebRootPath + @"\excel\");
      string time = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
      string excelPath = @"表名" + time + ".xls";
           //表格完整路径
          string filePath = Path.Combine(webRootPath + excelPath);
       //列名标题
       Dictionary dicColumns = new Dictionary();
       dicColumns.Add("aaa", "标题1");
       dicColumns.Add("bbb", "标题2");
       dicColumns.Add("ccc", "标题2");
       dicColumns.Add("ddd", "标题4");
     
       var ex = ExcelNPOIHelper.ExportE(filePath, "表名", list, dicColumns, 0);
       if (ex == false)
       {
           //导出失败
           return  this.Ok(-1);
       }
       else
       {

          //一、直接访问下载文件流
           指定路径字符串的扩展名(包括句点“.”)
           //string fileExt = Path.GetExtension(excelPath);
           //var stream = System.IO.File.OpenRead(filePath); //Path.GetExtension

           获取文件的ContentType
           //var provider = new FileExtensionContentTypeProvider();
           文件扩展名到 MIME 内容类型的映射。
           //var mime = provider.Mappings[fileExt];
            var downloadName = Path.GetFileName(addrUrl);
           //return File(stream, mime, excelPath);

          //二、返回下载路径
           return this.Ok(filePath);
       }

工具类

 public static bool ExportE(string output,string fileName, List datalist, Dictionary name, int version = 0) where T : class
        {
            if (datalist.Count <= 0)
            {
                return false;
            }
            //HSSFWorkbook => xls
            //XSSFWorkbook => xlsx
            HSSFWorkbook hssf = new HSSFWorkbook();//2007一下版本
            XSSFWorkbook xssf = new XSSFWorkbook();//2007以上版本
            IWorkbook workbook = null;
            if (version == 0)
            {
                workbook = hssf;
            }
            else
            {
                workbook = xssf;
            }
            //设置工作簿的名称
            fileName = string.IsNullOrEmpty(fileName) ? "sheet1" : fileName;
            //创建工作表
            ISheet sheet = workbook.CreateSheet(fileName);//名称自定义

            PropertyInfo[] propertyInfos = datalist[0].GetType().GetProperties();//获取公共属性


            ICellStyle styleTitle = workbook.CreateCellStyle();
            styleTitle.WrapText = true;//自动换行

            IRow cellsColumn = null;
            IRow cellsData = null;
            int cellsIndex = 0;
            

            //列名标题
            cellsColumn = sheet.CreateRow(cellsIndex);
            int index = 0;
            Dictionary columns = new Dictionary();
            foreach (var item in name)
            {
                cellsColumn.CreateCell(index).SetCellValue(item.Value);
                sheet.SetColumnWidth(index, 10 * 256);//设置对应列宽(单元格索引从0开始,后面接宽度)
                columns.Add(item.Value, index);
                index++;
            }
            cellsIndex += 1;
            //循环数据
            foreach (var item in datalist)
            {
                cellsData = sheet.CreateRow(cellsIndex);
                for (int i = 0; i < propertyInfos.Length; i++)
                {
                    if (!name.ContainsKey(propertyInfos[i].Name)) continue;
                    //这里可以也根据数据类型做不同的赋值,也可以根据不同的格式参考上面的ICellStyle设置不同的样式
                    object[] entityValues = new object[propertyInfos.Length];
                    entityValues[i] = propertyInfos[i].GetValue(item);
                    if (entityValues[i]==null)
                    {
                        continue;
                    }
                    //获取对应列下标
                    index = columns[name[propertyInfos[i].Name]];
                    sheet.SetColumnWidth(index, 20 * 256);//设置对应列宽(单元格索引从0开始,后面接宽度) 
                    cellsData.CreateCell(index).SetCellValue(entityValues[i].ToString());
                }
                cellsIndex++;
            }


            //保存Excel文件 //输出内容 指定路径
            using (FileStream fs = File.OpenWrite(output))
            {
                workbook.Write(fs);
                return true;
            }
        }
 

你可能感兴趣的:(NPOI导出,linq,c#,.netcore)