How to create and automatically download Excel file with c#.

1023 6 Reputation points
2021-10-14T18:44:23.01+00:00

Hello,

I would like to create a sheet and then download it. I wrote the code, but unfortunately no download works.

var memoryStream = new MemoryStream();

using (ExcelPackage package = new ExcelPackage(memoryStream))
{
    ExcelWorksheet worksheet;
    worksheet = package.Workbook.Worksheets.Add(name);

    worksheet.Name = name;

    for (int i = 0; i < nameColumns.Length; i++)
    {
        worksheet.Cells[1, i + 1].Value = nameColumns[i];
    }

    package.Save();
}

memoryStream.Position = 0;
var contentType = "application/octet-stream";
var fileName = "fileName.xlsx";
return File(memoryStream, contentType, fileName);

Regards

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2021-10-15T03:20:58.903+00:00

    Hi @1023 ,

    What do you mean about the download not work, is there any error message?

    Based on your code, it seems that you are using the EPPlus package to export data to excel, right? If that is the case, please check the EPPlus license.

    I create an Asp.net 5 MVC application with the following code (use the Polyform Noncommercial license), everything works well on my side.

        public IActionResult DownloadExcelEPPlus()  
        {  
            // query data from database     
            var list = new List<UserInfo>()  
            {  
                new UserInfo { UserName = "catcher", Age = 18 },  
                new UserInfo { UserName = "james", Age = 20 },  
            };  
            var stream = new MemoryStream();  
            //required using OfficeOpenXml;  
    
            // If you use EPPlus in a noncommercial context  
            // according to the Polyform Noncommercial license:  
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;  
            using (var package = new ExcelPackage(stream))  
            {  
                var workSheet = package.Workbook.Worksheets.Add("Sheet1");  
                workSheet.Cells.LoadFromCollection(list, true);  
                package.Save();  
            }  
            stream.Position = 0;  
            string excelName = $"UserList-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";  
    
            return File(stream, "application/octet-stream", excelName);    
            //return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);  
        }  
        public IActionResult Privacy()  
        {  
            return View();  
        }  
    

    Index.cshtml:

    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="DownloadExcelEPPlus">Download Excel Via EPPlus</a>  
    

    The result as below:

    140689-image.png

    Finally, if the above method still not working, you could try to use ClosedXML to export data to excel file.

    You can refer the following steps and sample code:

    In the Asp.net 5 MVC application, install the ClosedXML package via the Nuget.

    Index.cshtml:

    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="DownloadExcel">Download Excel</a>  
    

    Action method:

        //using closedxml  
        public IActionResult DownloadExcel()  
        {  
            List<Author> authors = new List<Author>  
            {  
                new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" },  
                new Author { Id = 2, FirstName = "Steve", LastName = "Smith" },  
                new Author { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}  
            };  
    
            //required using ClosedXML.Excel;  
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
            string fileName = "authors.xlsx";  
            try  
            {  
                using (var workbook = new XLWorkbook())  
                {  
                    IXLWorksheet worksheet =  
                    workbook.Worksheets.Add("Authors");  
                    worksheet.Cell(1, 1).Value = "Id";  
                    worksheet.Cell(1, 2).Value = "FirstName";  
                    worksheet.Cell(1, 3).Value = "LastName";  
                    for (int index = 1; index <= authors.Count; index++)  
                    {  
                        worksheet.Cell(index + 1, 1).Value = authors[index - 1].Id;  
                        worksheet.Cell(index + 1, 2).Value = authors[index - 1].FirstName;  
                        worksheet.Cell(index + 1, 3).Value = authors[index - 1].LastName;  
                    }  
                    //required using System.IO;  
                    using (var stream = new MemoryStream())  
                    {  
                        workbook.SaveAs(stream);  
                        var content = stream.ToArray();  
                        return File(content, contentType, fileName);  
                    }  
                }  
            }  
            catch (Exception ex)  
            {  
                return Error();  
            }  
        }  
    

    The result as below:

    140793-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.