Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Excel with multiple tabs [duplicate]

Tags:

c#

excel

linq

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?

like image 268
Freddy Avatar asked Aug 14 '13 13:08

Freddy


1 Answers

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.

like image 104
Dr Rob Lang Avatar answered Oct 03 '22 11:10

Dr Rob Lang