Programmatically Attaching an Excel Document to an Email in .NET

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);
    }

About Antonio Zugno
Web Developer - Experienced with HTML, C#, VB, JavaScript, jQuery, MS SQL, XML, WordPress, PHP, and Adobe Flash.

Leave a comment