【问题标题】:Generic Excel Generator function for EPPlusEPPlus 的通用 Excel 生成器函数
【发布时间】:2012-11-22 11:23:11
【问题描述】:

如何为您的 LINQ 查询构建通用 EPPlus 电子表格函数?

更新:特别需要 ASP.NET MVC 应用程序。

【问题讨论】:

    标签: c# asp.net-mvc linq epplus


    【解决方案1】:

    我所做的只是创建一个接受列表的通用函数。我使用反射来获取属性列表,这将成为我们的列标题。最后,我只是让 EPPlus 完成所有繁重的工作。

    void ListToExcel<T>(List<T> query)
        {            
            using (ExcelPackage pck = new ExcelPackage())
            { 
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Result");
    
                //get our column headings
                var t = typeof(T);
                var Headings = t.GetProperties();
                for (int i = 0; i < Headings.Count(); i++)
                {
    
                    ws.Cells[1, i+1].Value = Headings[i].Name;
                }
    
                //populate our Data
                if (query.Count() > 0)
                {
                    ws.Cells["A2"].LoadFromCollection(query);
                }
    
                //Format the header
                using (ExcelRange rng = ws.Cells["A1:BZ1"])
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                    rng.Style.Font.Color.SetColor(Color.White);
                }
    
                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
                Response.End();
            }
        }
    

    【讨论】:

      【解决方案2】:

      现在有一种更简单的方法可以使用 LoadFromCollection 方法实现此目的。

      public void ExportToExcel(IEnumerable<Employee> employees, FileInfo targetFile)
      {
          using (var excelFile = new ExcelPackage(targetFile))
          {
              var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");
              worksheet.Cells["A1"].LoadFromCollection(Collection: employees, PrintHeaders: true);
              excelFile.Save();
          }
      }
      

      示例取自这里:http://gruffcode.com/2013/10/30/simple-excel-export-with-epplus/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多