其他分享
首页 > 其他分享> > .net 根据List生成Excel

.net 根据List生成Excel

作者:互联网

 

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

 

/// <summary>
    /// 将List转化为Excel
    /// </summary>
    /// <typeparam name="T">类型</typeparam>
    /// <param name="source">数据源</param>
    /// <param name="SavePath">保存地址</param>
    public static void ToExcel<T>(this IEnumerable<T> 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<test>();
          list.ToExcel(SavePath);

 

标签:string,int,Excel,List,item,SavePath,sheet1,net,dp
来源: https://www.cnblogs.com/work-code/p/15974761.html