C#-.NET Core 2从内存流下载Excel文件

我当时在.NET Core项目中工作,当时我应该从记录创建电子表格文件并下载它而不将其保存在服务器中.搜索上述标题并没有多大帮助,但给出了一些指示.另外,ASP.NET中使用的大多数方法在.NET Core中均不起作用.因此,我终于可以想出一个效果很好的解决方案.我将在下面的答案中与那些愿意像我一样进行搜索的人分享.

解决方法:

首先,您将需要安装EPPlus.Core软件包.如果要通过Package Manager控制台安装它,则可以执行以下操作:

Install-Package EPPlus.Core

然后为OfficeOpenXml添加using语句:

using OfficeOpenXml;

然后,用于下载文件的示例方法将如下所示:

using OfficeOpenXml;

namespace MyProject.Controllers
{
    public class SubscribersController : Controller
    {
        private readonly ApplicationDbContext _context;

        public SubscribersController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> ExportToExcel()
        {
            var stream = new System.IO.MemoryStream();
            using (ExcelPackage package = new ExcelPackage(stream))
            {
                var subscribers = await _context.Subscribers.ToListAsync();                        

                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Subscribers");

                worksheet.Cells[1, 1].Value = "Name";
                worksheet.Cells[1, 2].Value = "Email";
                worksheet.Cells[1, 3].Value = "Date Subscribed";
                worksheet.Row(1).Style.Font.Bold = true;

                for (int c = 2; c < subscribers.Count + 2; c++)
                {
                    worksheet.Cells[c, 1].Value = subscribers[c - 2].Name;
                    worksheet.Cells[c, 2].Value = subscribers[c - 2].Email;
                    worksheet.Cells[c, 3].Value = subscribers[c - 2].DateCreated.ToString();
                }

                package.Save();
            }

            string fileName = @"Subscribers.xlsx";
            string fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            stream.Position = 0;
            return File(stream, fileType, fileName);
        }
    }
}
上一篇:使用DataContext和ItemsSource将数据源绑定到ListView上的区别


下一篇:Protobuf在各种环境中使用的总结