Using Save with Asp.net MVC

Hi

I was using
workbook.Save(“test.xls”, FileFormatType.Excel2003, SaveType.OpenInExcel, response)
with normal asp.net and everything worked fine. but due to business decision we are now using mvc. but mvc response object is Responsebase, so it doesn’t work. I am now using stream as

Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“Content-disposition”, “attachment; filename=OrderEntry1.xls”);
Response.Clear();
Response.BufferOutput = true;
System.IO.Stream stream = Response.OutputStream;
workbook.Save(stream, FileFormatType.Excel2003);
Response.Flush();
return new EmptyResult();

this generates a corrupted file. Can you please advice

Thanks…

p.s.
My Environment is ASP.NET 3.5 with MVC 1.0.
Aspose.Cells 4.7.1.24

Hi,

The component should work fine with Asp.net mvc. Could you try to remove all coding lines about Aspose.Cells and simply export the excel file with .NET’s System.IO objects if it works fine. In this way, you may trace your issue.


Thank you.

I know this is a fairly old post but I was looking for exactly the same answer and there does not appear to be many questions regarding MVC in the forum at the moment.

I managed to get this working correctly so figured I would post the result in case anyone else is looking.

As has been mentioned, you need to use a stream to output the resulting Excel file to the browser. The following code creates a basic Excel file from the controller and uses the Save method of the workbook to save the file to a stream. This stream is then outputted to the OutputStream of the ResponseBase object.



Function ExportExcelFile() As ActionResult

Dim workbook As New Workbook
Dim workSheet As Worksheet = workbook.Worksheets(“Sheet1”)

worksheet.Cells(0, 0).PutValue(“Test String”)

Dim stream As New System.IO.MemoryStream
Dim fileName As String = “Test.xls”

workbook.Save(stream, FileFormatType.Excel97To2003)

ExportExcelFileToResponse(stream, fileName)

'Return whatever is applicable
Return Nothing

End Function

Private Sub ExportExcelFileToResponse(ByVal stream As System.IO.MemoryStream, ByVal fileName As String)

ControllerContext.HttpContext.Response.Clear()
ControllerContext.HttpContext.Response.AddHeader(“cache-control”, “private”)
ControllerContext.HttpContext.Response.AddHeader(“Content-disposition”, “attachment; filename=” & fileName & “;”)
ControllerContext.HttpContext.Response.AddHeader(“Content-type”, “application/vnd.ms-excel”)

stream.WriteTo(ControllerContext.HttpContext.Response.OutputStream)

End Sub

An approach that I've used and simpler is:

book.Save(stream,SaveFormat.Excel97To2003);

stream.Position = 0;

return File(stream, "application/vnd.ms-excel", "junk.xls");