Sunday, December 6, 2009

ASP.NET - save content as ,excel file

Below is an example which indicates how to save content to excel file. It will pop-up a window to ask user to specify proper directory to store the file.

protected void Button1_Click(object sender, EventArgs e)
{
// make sure nothing is in response stream
Response.Clear();
Response.Charset = "";

// set MIME type to be Excel file.
Response.ContentType = "application/vnd.ms-excel";

// add a header to response to force download (specifying filename)
Response.AddHeader("Content-Disposition", "attachment; filename=\"MyFile.xls\"");

// Send the data. Tab delimited, with newlines.
Response.Write("Col1\tCol2\tCol3\tCol4\n");

Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");

// Close response stream.
Response.End();
}

No comments: