Saturday, 8 July 2017

c# - Linq to Excel with multiple tabs




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?


Answer



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(string separator, IEnumerable 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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...