2

I am able to save a single value into excel but I need help to save a full list/array into an excel sheet.

Code I have so far:

var MovieNames = session.Query<Movie>()
                          .ToArray();

List<string> MovieList = new List<string>();

foreach (var movie in MovieNames)
 {                   
  MovieList.Add(movie.MovieName);               
 }

//If I want to print a single value or a string, 
//I can use the following to print/save to excel
// How can I do this if I want to print that entire
//list thats generated in "MovieList" 

return File(new System.Text.UTF8Encoding().GetBytes(MovieList), "text/csv", "demo.csv");

2 Answers 2

4

You could use FileHelpers to serialize some strongly typed object into CSV. Just promise me to never roll your own CSV parser.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for very funny stuff linked("That ringing in your ears is Jamie Zawinski saying "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.")
@TimSchmelter, yeah, this is so damn true.
@DarinDimitrov To be honest I have never seen anyone try to parse csv with regular expressions.
2

If you mean you want to create a .csv file with all movie names in one column so you can open it in Excel then simply loop over it:

byte[] content;

using (var ms = new MemoryStream())
{
    using (var writer = new StreamWriter(ms))
    {
        foreach (var movieName in MovieList)
            writer.WriteLine(movieName);
    }

    content = ms.ToArray();
}

return File(content, "text/csv", "demo.csv");

Edit

You can add more columns and get fancier with your output but then you run into the problem that you have check for special characters which need escaping (like , and "). If you want to do more than just a simple output then I suggest you follow @Darins suggestion and use the FileHelpers utilities. If you can't or don't want to use them then this article has an implementation of a csv writer.

3 Comments

I am getting an exception - "Cannot access a closed stream"
@ZVenue Sorry, I forgot, StreamWriter closes the underlying stream when being disposed. I corrected the code.
thank you.. that works. Is there a way, I can format the output using this method? Like have more than one values outputted and have labels etc..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.