Friday, 21 January 2011

Send generated excel on the web using HTTPReponse in dot.net

Problem:
You want to send a generated excel file as web response to the client.




Follow these steps:
  1. Create your Excel object with you favorite library (We use the open-source NPOI)
  2. Get a memoryStream from your object.
  3. Get a byte array buffer from the stream.
  4. Give this array over to the HTTPResponse object.
  5. Finally clean up after you.

Here is the code :
public void SendExcel(HttpResponse response)
{
    try
    {
        // 1)
        HSSFWorkbook book = CreateExcelWorkbook();
        // 2)
        MemoryStream file = new MemoryStream();
        book.Write(file);

        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", string.Format("attachment;filename=test.xls"));
        response.Clear();
        // 3) 4)
        response.BinaryWrite(WriteToStream(book).GetBuffer());
    }
    // 5)
    finally
    {
        response.Flush();
        response.Close();
    }
    response.End();
}

1 comment:

Anonymous said...

Does that mean you use twice the amount of memory needed to store the resulting file? (One time in the MemoryStream, the second time in the array of bytes you generate)
Can't you write the result directly in the response stream?
(yes you can)