将对象导出到.xlsx到客户机asp.net核心

时间:2017-12-20 02:05:48

标签: c# asp.net export epplus filestreamresult

我目前正在将对象导出到.xlsx文件中。这非常接近我所需要的,Export xlsx in ASP.NET Core ,但问题是 - 这是导出到本地项目文件夹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文件夹,然后再使用工作表网址返回filestreamresult。我不知道如何获取工作表的url以传递filestreamresult函数。

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

2 个答案:

答案 0 :(得分:1)

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

var stream = new MemoryStream(package.GetAsByteArray());
return File(stream.ToArray(), "application/vnd.ms-excel", sFileName);

答案 1 :(得分:0)

在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/