Adding headers to web response before calling workbook.save()

Hello there,


I have a procedure like below.

private static void ExportHttpExcel(Workbook _workbook, string _filename)
{
_workbook.Save(_filename + GetExtention(FileFormatType.Excel2003), FileFormatType.Excel2003, Aspose.Cells.SaveType.OpenInBrowser, System.Web.HttpContext.Current.Response);
}

I need to add “Content-Length” header to the response due to an exception being thrown in mobile devices. So, I have tried something like below,

//saving workbook to a stream
MemoryStream stream = new MemoryStream();
_workbook.Save(stream, FileFormatType.Excel2003);
stream.Seek(0, SeekOrigin.Begin);
Byte[] readBytes = new Byte[(int)stream.Length];
readBytes = stream.ToArray();

//adding header
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
if (readBytes != null)
response.AddHeader(“Content-Length”, readBytes.Length.ToString());
response.BinaryWrite(readBytes);

//call save
_workbook.Save(_filename + GetExtention(FileFormatType.Excel2003), FileFormatType.Excel2003, Aspose.Cells.SaveType.OpenInBrowser, response);

But it didn’t succeed. Workbook gets pushed to client (browser), but it’s empty.

Any help on this would be appreciated.

Thanks in advance.


Hi,

Thanks for your posting and using Aspose.Cells.

Please try the following code and see if it fixes your issue.

C#


//Save file and send to client browser using selected format
if (yourFileFormat == “XLS”)
{
workbook.Save(HttpContext.Current.Response, “output.xls”, ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));

}
else
{
workbook.Save(HttpContext.Current.Response, “output.xlsx”, ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
}

HttpContext.Current.Response.End();

Thank you for your reply.

What you have suggested doesn’t work for me because the version I have is 4.6. And, we cannot do an upgrade at this moment.

But, something like below works for me.

var book = new Aspose.Cells.Workbook(MapPath(“book1.xlsx”));
MemoryStream ms = new MemoryStream();
book.Save(ms, Aspose.Cells.SaveFormat.Excel97To2003); 
this.Response.ContentType = “application/vnd.ms-excel”;
this.Response.AddHeader(“content-disposition”, “attachment; filename=sample.xls”);
this.Response.AddHeader(“Content-Length”, ms.Length.ToString()); 
this.Response.BinaryWrite(ms.ToArray());
this.Response.End(); 

Hi Janaka,

Thanks for your posting and using Aspose.Cells.

It is good to know that you were able to sort out this issue. We also recommend you to upgrade your code to newer version so that you could make use of new features, enhancements and bug fixes. Let us know if you encounter any other issue, we will be glad to look into it and help you further.