Export GridView as excel into an email attachment

GridView in ASP.NET displays tabular data. We will explore how to export this data as an excel file. Let us assume that the GridView represents a report. And we want to send the report as an email attachment. Below code exports the GridView and prepares an email attachment.

protected void Submit_Click(object sender, EventArgs e)
{
    // Render the contents of the GridView into a string
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GridView1.RenderControl(htw);

    // Get the byte buffer from the string
    byte[] buffer = new byte[sb.Length];
    ASCIIEncoding enc = new ASCIIEncoding();
    buffer = enc.GetBytes(sb.ToString());

    // Create attachment from MemoryStream
    MemoryStream ms = new MemoryStream(buffer);
    Attachment attachment = new Attachment(ms, "GridReport.xls");
}

Render the GridView as a HTML string using the RenderControl method. RenderControl method accepts a HtmlTextWriter object. Compose the HtmlTextWriter from the StringWriter and StringBuilder objects. HTML string from GridView render is eventually written to the StringBuilder object.

From the HTML string, extract a buffer (of bytes) assuming ASCII encoding. Create a MemoryStream object from the byte buffer. Prepare the email attachment using the MemoryStream object.

Attachment is available in System.Net.Mail namespace. We attach this attachment to the Attachments collection of a MailMessage object.

MailMessage message = new MailMessage(
	   "sender@email.com",
	   "receiver@email.com",
	   "Annual report.",
	   "See the attached spreadsheet."
);
message.Attachments.Add(attachment);

 

Related Posts

Leave a Reply

Your email address will not be published.