Embedd_0913
Embedd_0913

Reputation: 16555

How to exporting data from a List<T> to excel file?

I have a List<Person> which is bound to a grid view. I want to export all the values to an excel file. My person class is as follows:

class Person
{
    public string Name { get; set; }
    public string City { get; set; }
    public int Age { get; set; }
}

Is there any way to do it? Please suggest....

Upvotes: 0

Views: 1616

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180788

Run through your list with a foreach loop, and create a CSV file, one line per person. CSV files can be opened directly by Excel.

Upvotes: 0

Andrew Keith
Andrew Keith

Reputation: 7563

you will need an SDK to save as the xlsx format. I dont know where to get the openxml sdk to do it, but here is a code snippet to save as a CSV which can be opened in excel as well.

List<Person> persons; // populated earlier
using(StreamWriter wr = new StreamWriter("myfile.csv"))
{
   foreach(Person person in persons)
   {
     wr.WriteLine(person.Name + "," + person.City + "," + person.Age);
   }
}

Upvotes: 1

Related Questions