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?

1

1 Answer 1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.