Send GridView as Excel attachment in Mail

 This code illustrates you how to send Gridview content as an Excel Attachment in Email.

 

The Gridview Markup looks like this…

 

 

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="GridMail.aspx.cs" Inherits="GridMail" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

     <asp:Button ID="btnMail" runat="server" Text="Send Mail"

            />

        <asp:Label ID="lbldisplay" runat="server" Text="Label"></asp:Label>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

            DataSourceID="SqlDataSource1">

            <Columns>

              

                <asp:BoundField DataField="rollno" HeaderText="rollno"

                    SortExpression="rollno" />

                <asp:BoundField DataField="stuname" HeaderText="stuname"

                    SortExpression="stuname" />

                <asp:BoundField DataField="stufathername" HeaderText="stufathername"

                    SortExpression="stufathername" />

                <asp:BoundField DataField="parentmobileno" HeaderText="parentmobileno"

                    SortExpression="parentmobileno" />

                <asp:BoundField DataField="parentemail" HeaderText="parentemail"

                    SortExpression="parentemail" />

                <asp:BoundField DataField="classname" HeaderText="classname"

                    SortExpression="classname" />

                <asp:BoundField DataField="sectionname" HeaderText="sectionname"

                    SortExpression="sectionname" />

                

                <asp:BoundField DataField="gender" HeaderText="gender"

                    SortExpression="gender" />

            

                <asp:BoundField DataField="loginid" HeaderText="loginid"

                    SortExpression="loginid" />

            </Columns>

        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

            ConnectionString="<%$ ConnectionStrings:parentsalarmConnection %>"

            SelectCommand="SELECT top 10 * FROM [studentmaster] WHERE ([userid] = @userid) ORDER BY [loginid]">

            <SelectParameters>

                <asp:Parameter DefaultValue="1001" Name="userid" Type="String" />

            </SelectParameters>

        </asp:SqlDataSource>

    </div>

    </form>

</body>

</html>

 

 

Moving to code behind the function to convert Gridview content as Excel attachment is as follows:

 

public void fn_AttachGrid()

    {

        StringWriter stw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(stw);

        GridView1.RenderControl(hw);

        MailMessage mail = new MailMessage();

        mail.IsBodyHtml = true;

        mail.To.Add(new MailAddress("toMail@domain.com"));

        mail.Subject = "Sales Report";

        System.Text.Encoding Enc = System.Text.Encoding.ASCII;

        byte[] mBArray = Enc.GetBytes(stw.ToString());

        System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);

        mail.Attachments.Add(new Attachment(mAtt, "sales.xls"));

        mail.Body = "Hi PFA";

        SmtpClient smtp = new SmtpClient();

        mail.From = new MailAddress("fromMail@domain.com", "Your Name");

        smtp.Host = "mail.domain.com";

        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new System.Net.NetworkCredential(@"Username", "Password");

        smtp.EnableSsl = true;

        smtp.Send(mail);

        lbldisplay.Text = "Email Sent";

    }

 

Calling this method in the button click event will mail  you the Gridview data as Excel attachment.

CodeBehind :

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Net.Mail;

 

public partial class Csharp : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    public void fn_AttachGrid()

    {

        StringWriter stw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(stw);

        GridView1.RenderControl(hw);

        MailMessage mail = new MailMessage();

        mail.IsBodyHtml = true;

        mail.To.Add(new MailAddress("toMail@domain.com"));

        mail.Subject = "Sales Report";

        System.Text.Encoding Enc = System.Text.Encoding.ASCII;

        byte[] mBArray = Enc.GetBytes(stw.ToString());

        System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);

        mail.Attachments.Add(new Attachment(mAtt, "sales.xls"));

        mail.Body = "Hi PFA";

        SmtpClient smtp = new SmtpClient();

        mail.From = new MailAddress("fromMail@domain.com", "Your Name");

        smtp.Host = "mail.domain.com";

        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new System.Net.NetworkCredential(@"Username", "Password");

        smtp.EnableSsl = true;

        smtp.Send(mail);

        lbldisplay.Text = "Email Sent";

    }

 

 

 

    public override void VerifyRenderingInServerForm(Control control)

    {

               

    }

 

 

 

 

    protected void btnSendMail_Click(object sender, EventArgs e)

    {

 

        fn_AttachGrid();

 

    }

}

 

 

8 Comments

  • I am getting error as The operation has timed out

  • Thanks a ton Stanley..

    It worked for me as expexted..

  • hi
    I use this code i useful this code

    i sent some changes for anothe view


    coding

    GviewTranervna1.Visible = true;
    StringWriter stw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(stw);
    GviewTranervna1.RenderControl(hw);

    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.Subject = "sales Subject";
    System.Text.Encoding Enc = System.Text.Encoding.ASCII;
    byte[] mbarray = Enc.GetBytes(stw.ToString());
    string filenm = Path.Combine(Path.GetTempPath(), "vnareport.xls");
    using (FileStream fs = new FileStream(filenm, FileMode.Create))
    {
    fs.Write(mbarray, 0, mbarray.Length);
    }
    string reportnm = filenm;
    System.IO.MemoryStream matt = new System.IO.MemoryStream(mbarray, false);
    ApplicationClass outlook = new ApplicationClass();

    MailItem mitem = (MailItem)outlook.CreateItem(OlItemType.olMailItem);
    mail.Body = "Hi PFA";
    mitem.Attachments.Add(reportnm, (int)OlAttachmentType.olByValue, 1, reportnm);
    mitem.Display(false);
    SmtpClient smtp = new SmtpClient();

    GviewTranervna1.Visible = false;
    email.Visible = false;

  • Failure sending mail.smtp exveption was unhandles by user code.

    getg error on last be line at smtp.send(mail);

    plz reply solution for this problem.

  • Thanks a lot Stanly.. tat worked for me like charm.. :)

  • No me funciono el código :(

  • Thanks sir,
    You solve my problem

  • Thanks so much........its working fine

Comments have been disabled for this content.