如何使用mvc.net将数据从数据库导出到exel? [英] How to export data from database to exel using mvc.net?

查看:79
本文介绍了如何使用mvc.net将数据从数据库导出到exel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请在我的代码出错的地方帮助我。

我的excel文件只将数据库的最后一行添加到下载的excel文件中。



我尝试过:



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"));
    }
}

推荐答案

你没有递增计数所以你是只是不断覆盖同一行



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++;

}


这篇关于如何使用mvc.net将数据从数据库导出到exel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆