1

我目前正在将对象导出到 .xlsx 文件中。这与我需要的非常接近,在 ASP.NET Core 中导出 xlsx ,但问题是 - 这是导出到本地项目文件夹 wwwroot,我想导出到客户端机器。

我试过这个。

   private readonly IHostingEnvironment _hostingEnvironment;

    public ImportExportController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpGet]
    [Route("Export")]
    public FileStreamResult Export()
    {
        string sWebRootFolder = _hostingEnvironment.WebRootPath;
        string sFileName = @"demo.xlsx";
        string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
        FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            // add a new worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            //First add the headers
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            //Add values
            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save(); //Save the workbook.
        }


        FileStream RptStream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open, FileAccess.Read);
        return new FileStreamResult(RptStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }

但似乎我需要将工作表导出到 wwwroot 文件夹,然后使用工作表 url 返回 filestreamresult。而且我不知道如何让工作表的 url 传入 filestreamresult 函数。

任何人都可以帮助我吗?我想在客户端机器上导出这个 .xlsx 而不是 wwwroot。

4

2 回答 2

1

在 asp.net Core 中有一个库,您可以使用名为“EPPlus”的库,通过添加包管理器控制台“Install-Package EPPlus -Version 4.5.2.1”下载其块,然后在控制器中使用以下代码

每行之前都有一个注释用于描述。

    public async Task<IActionResult>  Export()
    {
        await Task.Yield();

        //Lets we have object userInfo so we will fill it
        var list = new List<UserInfo>()
        {
            new UserInfo { UserName = "catcher", Age = 18 },
            new UserInfo { UserName = "james", Age = 20 },
        };

        // Then use system.IO.MemeoryStream
        var stream = new MemoryStream();

        //Then generate the Sheet by below code "using OfficeOpenXml;" from EPPlus nugget
        using (var package = new ExcelPackage(stream))
        {
            //name the sheet "Sheet1"
            var workSheet = package.Workbook.Worksheets.Add("Sheet1");

            // simple way
            workSheet.Cells.LoadFromCollection(list, true);

            //// mutual
            //workSheet.Row(1).Height = 20;
            //workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            //workSheet.Row(1).Style.Font.Bold = true;
            //workSheet.Cells[1, 1].Value = "No";
            //workSheet.Cells[1, 2].Value = "Name";
            //workSheet.Cells[1, 3].Value = "Age";

            //int recordIndex = 2;
            //foreach (var item in list)
            //{
            //    workSheet.Cells[recordIndex, 1].Value = (recordIndex - 1).ToString();
            //    workSheet.Cells[recordIndex, 2].Value = item.UserName;
            //    workSheet.Cells[recordIndex, 3].Value = item.Age;
            //    recordIndex++;
            //}

            package.Save();
        }
        stream.Position = 0;

        //Name the file which will download
        string excelName = $"UserInfoList-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";

        //Then download 
        return File(stream, "application/octet-stream", excelName);
    }

参考链接 https://www.c-sharpcorner.com/article/using-epplus-to-import-and-export-data-in-asp-net-core/

于 2019-10-30T15:21:18.540 回答
1

尝试将文件写入内存流并让您的方法返回 FileContentResult 对象(通过 Controller.File 方法):

var stream = new MemoryStream(package.GetAsByteArray());
return File(stream.ToArray(), "application/vnd.ms-excel", sFileName);
于 2017-12-20T03:54:30.787 回答