.net 根据List生成Excel


注:此功能依托于NPOI,需要引用NPOI包。

/// 
    /// 将List转化为Excel
    /// 
    /// 类型
    /// 数据源
    /// 保存地址
    public static void ToExcel(this IEnumerable source, string SavePath) where T : class
    {
      IWorkbook book = new XSSFWorkbook();//根据原模板初始化临时模板
      ISheet sheet1 = book.CreateSheet();//sheet页
      sheet1.CreateRow(0);

      int i = 0;
      foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
      {
        string a = dp.Name;
        sheet1.GetRow(0).CreateCell(i).SetCellValue(a);
        i++;
      }
      int j = 1;
      foreach (T item in source)
      {
        sheet1.CreateRow(j);
        int k = 0;
        foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
        {
          var val = dp.GetValue(item).ToString();
          sheet1.GetRow(j).CreateCell(k).SetCellValue(dp.GetValue(item)?.ToString());
          k++;
        }
        j++;
      }

      using (FileStream fileSave = new FileStream(SavePath, FileMode.Create, FileAccess.Write))
      {
        book.Write(fileSave);
      }
    }

调用方法

          string filePath = AppDomain.CurrentDomain.BaseDirectory + $"Files/{DateTime.Now.ToString("yyyyMMdd")}";
          string SavePath = filePath + "\\" + fileName;
          var list = new List();
          list.ToExcel(SavePath);