【问题标题】:Generate export excel-table using EPPlus.Core使用 EPPlus.Core 生成导出 excel 表
【发布时间】:2019-04-09 15:58:02
【问题描述】:

我想创建将从我的存储过程生成 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 函数返回什么类型?如果我需要提供任何信息和想法,我将不胜感激。

【问题讨论】:

  • 我想你要找的是byte[]。您可以使用MemoryStream 将 EPPlus 文件保存到字节数组而不是实际文件,然后返回该字节数组。

标签: c# excel asp.net-core export


【解决方案1】:

对于File,它是来自ControllerBase 的基本方法,它将返回FileContentResult。如果您更喜欢使用File,您可以实现FileResult variants 中的代码。

IMO,我建议你从public async Task OnPostExport(int year) 返回byte[],然后构造响应File 就像

public async Task<byte[]> OnPostExport(int year)
{
    //logic
    return filebytearray;
}


var dt = await _exportService.OnPostExport(1);
return File(dt, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多