Programmatically Attaching an Excel Document to an Email in .NET
August 9, 2011 Leave a comment
Periodically clients will ask me to send them a report from a database. Instead of creating an Excel spreadsheet from the database and then attaching it to an email, I have automated the process. The following function will take in a MailMessage object by reference along with a DataGrid object and filename string. The function then attaches an Excel file containing the DataGrid contents to the MailMessage object.
This function uses the following inclusions: System.Net, System.IO, System.Net.Mail, System.Collections, System.Collections.Generic
// Function attaches a DataGrid to Email in Excel Format private void AttachDataGridToEmail(ref MailMessage mailMessage, DataGrid dataGrid, String filename) { MemoryStream ms = new MemoryStream(); System.IO.StringWriter stringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); dataGrid.RenderControl(htmlWriter); byte[] excelFile = StrToByteArray(stringWriter.ToString()); ms.Write(excelFile, 0, excelFile.Length); ms.Position = 0; Attachment attachment = new Attachment(ms, filename + ".xls", "application/vnd.xls"); mailMessage.Attachments.Add(attachment); }