Mecit Atmaca

Thoughts on Software & Process Engineering

Server-side Office Integration -6: Rendering Excel Data on cross browsers

In order to display data generated in prior calls as an Excel file on the user browser, we need to set 2 properties of the Response object (in its simplest form):

  1. ContentType to 'application/vnd.ms-excel'
  2. EnableViewState to 'False'

Then with the header information, we send the data into the client.

/// <summary>
/// Displays data (if exist) as an Excel spreadsheet on user browser.
/// </summary>
/// <param name="bytes">The bytes to be the content of the excel spreadsheet</param>
private void DisplayNewExcelFile(byte[] bytes)
{
    if (bytes == null || bytes.Length == 0)
    {
        litMsg.Text = "No data found.";
        return;
    }

    Response.ClearHeaders();
    Response.ContentType = "application/vnd.ms-excel";
    Page.EnableViewState = false;
    Response.AddHeader("content-disposition", "attachment;filename=PersonAddress_Modified.xlsx");
    Response.BinaryWrite(bytes);

    try
    {
        Response.End();
        //this causes a System.Threading.ThreadAbortException, which ends the current request.
    }
    catch { }
}

 

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)