7

I use Entity Framework together with Linq to fill my gridviews. I would like to get the same data I get from the Linq in an excel. Also a second tab in the same excel sheet should come from another Linq query.

Whats the easiest and best way to do this?

Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55
Freddy
  • 960
  • 1
  • 20
  • 46

1 Answers1

3

There are two parts to this. The first is to serialise your linq collection to CSV. You can serialise an enumerable method like this:

public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
    Type t = typeof(T);
    FieldInfo[] fields = t.GetFields();

    string header = String.Join(separator, fields.Select(f => f.Name).ToArray());

    StringBuilder csvdata = new StringBuilder();
    csvdata.AppendLine(header);

    foreach (var o in objectlist) 
        csvdata.AppendLine(ToCsvFields(separator, fields, o));

    return csvdata.ToString();
}

That method won't help you with deep objects but it will get you to CSV. The second stage is to build the XSLX format (assuming that 2 CSVs won't be enough). For that I would recommend the Open XML SDK from Microsoft to build the two worksheets from your CSV string. I also like this answer for building an Excel spreadsheet.

Community
  • 1
  • 1
Dr Rob Lang
  • 6,659
  • 5
  • 40
  • 60