使用 EPPlus.Core 生成导出 excel 表

我想创建将从我的存储过程生成 excel 表的服务。我正在寻找https://www.talkingdotnet.com/import-export-excel-asp-net-core-2-razor-pages/它直接用于剃须刀页面,但我需要创建服务(在我的业务层并将其提供给控制器)。


我遇到的问题是,在本教程中它是IActionResult从函数返回的:


public async Task<IActionResult> OnPostExport()

{

    //logic

    return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);

}

有关模式详细信息,请参阅https://www.talkingdotnet.com/import-export-excel-asp-net-core-2-razor-pages/。


我试着写这段代码:


public class ExportService

{      

    private IHostingEnvironment _hostingEnvironment;


    public ExportService(IHostingEnvironment hostingEnvironment)

    {

        _hostingEnvironment = hostingEnvironment;

    }


    public async Task OnPostExport(int year)

    {

        //logic

        return File(memory, "application/vnd.openxmlformats- 

        officedocument.spreadsheetml.sheet", sFileName);

    }

它不起作用,因为“返回文件”- PageModel 的功能在教程中是如何工作的。我想从我的服务中将文件返回给控制器。我应该从我的OnPostExport函数返回什么类型?对于我需要做的任何信息和想法,我将不胜感激。


茅侃侃
浏览 205回答 1
1回答

呼啦一阵风

对于File,它是ControllerBase将返回的基本方法FileContentResult。如果您更喜欢使用File,您可以实现FileResult 变体中的代码。IMO,我建议你byte[]从那里回来public async Task OnPostExport(int year),然后构建File像这样 的回应public async Task<byte[]> OnPostExport(int year){&nbsp; &nbsp; //logic&nbsp; &nbsp; return filebytearray;}var dt = await _exportService.OnPostExport(1);return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
打开App,查看更多内容
随时随地看视频慕课网APP