【问题标题】:c# Asp.NET MVC downloading excel file using FileStreamResultc# Asp.NET MVC 使用 FileStreamResult 下载 excel 文件
【发布时间】:2017-03-23 11:03:24
【问题描述】:

我需要构建一个方法,它将接收模型,从中构建 excel(构建和接收部分没有问题),然后使用内存流导出(让用户下载它)(不保存在服务器上)。我是 ASP.NET 和 MVC 的新手,所以我找到了指南并将其构建为一个教程项目:

    public FileResult Download()
    {
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

        object misValue = System.Reflection.Missing.Value;

        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        xlWorkSheet.Cells[1, 1] = "ID";
        xlWorkSheet.Cells[1, 2] = "Name";
        xlWorkSheet.Cells[2, 1] = "1";
        xlWorkSheet.Cells[2, 2] = "One";
        xlWorkSheet.Cells[3, 1] = "2";
        xlWorkSheet.Cells[3, 2] = "Two";


        var path = "C:\\Work-Work\\TestFolder\\XCLbuildTry1\\csharp-Excel.xls";
        xlWorkBook.SaveAs(path);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        Marshal.ReleaseComObject(xlWorkSheet);
        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);
        return File(path, "application/vnd.ms-excel", "WidgetData.xlsx");
    }

现在我需要更改此代码以使此方法发送我的 excel 文件而不将我的 excel 文件保存在服务器上。我曾尝试在堆栈上搜索一些指南和答案,但现在我找不到可以实施的解决方案。

我认为我应该使用FileStreamResult,但所有指南都没有提供有关创建文件并将其插入流中的具体信息。

【问题讨论】:

    标签: c# asp.net-mvc-4 filestreamresult


    【解决方案1】:

    不幸的是,Microsoft.Office.Interop.Excel.Workbook 接口 (msdn) 似乎不允许您将工作簿转换为内存流。

    但是,过去我使用过一个外部库 EPPlus,它的效果非常好。

    请参阅下面的使用 EPPlus 的代码,它不需要您将文件保存在服务器上。


    业务逻辑

    public MemoryStream Download() {
        MemoryStream memStream;
    
        using (var package = new ExcelPackage()) {
            var worksheet = package.Workbook.Worksheets.Add("New Sheet");
    
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[2, 1].Value = "1";
            worksheet.Cells[2, 2].Value = "One";
            worksheet.Cells[3, 1].Value = "2";
            worksheet.Cells[3, 2].Value = "Two";  
    
            memStream = new MemoryStream(package.GetAsByteArray());
        }
    
        return memStream;
    }    
    

    控制器

    public FileStreamResult Download() {
        var memStream = BusinessLogic.Download();
        result File(memStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多