Response.end不起作用

时间:2016-02-08 07:56:09

标签: c# response openxml

我尝试使用.xlsx和OpenXml下载Response.End()文档。 但没有任何反应。它停留在Response.End()

public void DownloadStudents(int InstituteId, int DepartmentId)
{ 
     var memoryStream = new MemoryStream();

     using (var spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
     {
         //Some code
         foreach (var line in users)
         {
              // Fill
         }

         spreadsheetDocument.WorkbookPart.Workbook.Save(); 
    } 

    var excelName = "Title.xlsx";

    Response.Clear();
    Response.CacheControl = "Private"; 
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Type", "application/octet-stream");
    Response.AppendHeader("content-disposition",string.Format("attachment; filename={0}; size={1}", excelName, memoryStream.Length));
    Response.BinaryWrite(memoryStream.ToArray());

    **//Problem is here.**  
    Response.End(); // In this line nothing happens
}

尝试使用Response.Flush()时会出现同样的问题。 如果我使用CompleteRequest()代替Response.End() .xlsx文件为空

1 个答案:

答案 0 :(得分:0)

这适用于所有文件:

    public static void outputFile(FileContentResult file, String contentDisposition)
    {
        var context = System.Web.HttpContext.Current;
        file.FileDownloadName = contentDisposition;
        context.Response.Clear();
        context.Response.ClearContent();
        context.Response.ClearHeaders();
        context.Response.AppendHeader("content-disposition", contentDisposition);
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.ContentType = file.ContentType;
        context.Response.AppendHeader("content-length", file.FileContents.Length.ToString());
        context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
        context.Response.Flush();
        context.ApplicationInstance.CompleteRequest();
    }

FileContentResult是在MVC中使用Controller类的File方法的结果。

我也相信你所缺少的是在尝试输出之前关闭工作簿。

我建议在尝试将视频输出到视图之前,先将spreadsheetDocument.Close()后跟memoryStream.Flush()添加到代码中。

contentDisposition只是String.Format(“attachment; filename = {0}”,fileName)。

此外,Response.End()会抛出错误,因此请始终使用另一个错误。