Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
please kindly assist me where i have gone wrong with my code.
My excel file only adds the last line of the database to excel file which is downloaded.

What I have tried:

Below is my is my controller with my Export void function.

<pre>EntertainmentEntities dbmodel = new EntertainmentEntities();
        private int count = 1;

public void Export()
{
    using (var p = new ExcelPackage())
    {
        List<MusicViewModel> myMusicList = dbmodel.Music.Select(x => new MusicViewModel
        {
            ID = x.ID,
            Artist = x.Artist,
            Song = x.Song,
            Genre = x.Genre,
            MusicDate = x.MusicDate
        }).ToList();

        var ws = p.Workbook.Worksheets.Add("MySheet");
        ws.Cells["A1"].Value = "testing my code";
        foreach (var item in myMusicList)
        {
            ws.Cells[string.Format("A{0}", count)].Value = item.ID;
            ws.Cells[string.Format("B{0}", count)].Value = item.Artist;
            ws.Cells[string.Format("C{0}", count)].Value = item.Song;
            ws.Cells[string.Format("D{0}", count)].Value = item.Genre;
            ws.Cells[string.Format("E{0}", count)].Value = item.MusicDate;

        }

        p.SaveAs(new FileInfo(@"C:\Chazz Archives\myworkbook.xlsx"));
    }
}
Posted
Updated 10-Sep-18 0:30am

1 solution

You're not incrementing "count" so you're just constantly overwriting the same row

foreach (var item in myMusicList)
{
    ws.Cells[string.Format("A{0}", count)].Value = item.ID;
    ws.Cells[string.Format("B{0}", count)].Value = item.Artist;
    ws.Cells[string.Format("C{0}", count)].Value = item.Song;
    ws.Cells[string.Format("D{0}", count)].Value = item.Genre;
    ws.Cells[string.Format("E{0}", count)].Value = item.MusicDate;
    count++;

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900