Popular blog tags

  If this is asp.net-core then you are mixing web api versions. have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

 [Route("api/[controller]")]

        public class DownloadController : Controller

        {

            //GET api/download/12345abc

            [HttpGet("{id}"]

            public async Task<IActionResult> Download(string id)

            {

                var stream = await { { __get_stream_here__} }

                var response = File(stream, "application/octet-stream");

                // FileStreamResult

                return response;

            }

        }

2. return excel file

 [Route("api/[controller]")]
    [ApiController]
    public class ExecelController : ControllerBase
    {
       


        //come from:
        [Route("api/Execel/TOExecel")]
        public IActionResult TOExecel()
        {
            var list = new List<Test>();

            list.Add(new Test()
            {
                Id = 1,
                Name = "Test",
                Age = 22,

            });

            byte[] fileContents;
            using (ExcelPackage package = new ExcelPackage())
            {


                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(".Net Core 导出");


                worksheet.Cells[1, 1].Value = "序号";
                worksheet.Cells[1, 2].Value = "Id";
                worksheet.Cells[1, 3].Value = "名称";
                worksheet.Cells[1, 4].Value = "年龄";

                int i = 2;

                foreach (var item in list)
                {
                    worksheet.Cells["A" + i].Value = i - 1;
                    worksheet.Cells["B" + i].Value = item.Id;
                    worksheet.Cells["C" + i].Value = item.Name;
                    worksheet.Cells["D" + i].Value = item.Age;
                    i = i + 1;
                }

                fileContents = package.GetAsByteArray();
                if (fileContents == null || fileContents.Length == 0)
                {
                    return NotFound();
                }
            }
            return File(fileContents, "application/ms-excel", $"{Guid.NewGuid().ToString()}.xlsx");
        }
    }

    public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }