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.

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.


Export GridView as excel into an email attachment
Tagged on: