首页 > 解决方案 > 如何在 ASP.NET 和 VB.NET 中使用 Open XML 返回文件

问题描述

我有一个使用 VB.NET 的旧版 ASP.NET 3.5(不是 ASP.NET MVC)应用程序。当用户单击按钮时,我想下载一个 Excel 电子表格。我正在使用 OpenXML 库。我在 ASP.NET MVC 中使用了相同的功能,您可以使用 OpenXML 返回文件,如下所示:-

public FileContentResult GetCollectionsExcel()
{
    var collections = CurrentBroker.Collections;

            var model = new FinancialCollectionsModel(collections);

            var package = new ExcelPackage();
            var sheet = package.Workbook.Worksheets.Add("Collections");

   return File(package.GetAsByteArray(),"application/vnd.openxmlformatsofficedocument.spreadsheet.sheet", "Collections.xlsx");
}

它在传统的 ASP.NET 和 VB.NET 中是什么等价物?该方法的返回类型应该是什么,因为我们在 ASP.NET 中没有 FileContentResult。

标签: asp.net

解决方案


Access the response directly, write the data to the response stream and set the necessary headers

'...code removed for brevity

Dim response = HttpContext.Current.Response
response.ContentType = "application/vnd.openxmlformatsofficedocument.spreadsheet.sheet"
response.AppendHeader("Content-Disposition", "attachment; filename=""Collections.xlsx""")
response.BinaryWrite(package.GetAsByteArray())

推荐阅读