Tuesday, 8 October 2013

ASP.NET - Export Gridview data to excel and directly send a mail with exported excel file

On Control Event use this code in C#:

                        GridView gdvExportxls = new GridView();
                        gdvExportxls.DataSource = dtnew;
                        gdvExportxls.DataBind();
                        MemoryStream ms = new MemoryStream();
                        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
                        gdvExportxls.RenderControl(htmlWriter);
                        byte[] excelFile = System.Text.Encoding.ASCII.GetBytes(stringWriter.ToString());
                        ms.Write(excelFile, 0, excelFile.Length);
                        ms.Position = 0;

                        Attachment attachment = new Attachment(ms, "Test.xls", "application/vnd.xls");
                        SendMail(attachment);


          private void SendMail(Attachment excel)
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("brijesh.singh879@gmail.com")
            mail.Subject = "Export GridView to Excel";
            mail.Body = "mail with attachment";

            //System.Net.Mail.Attachment attachment;
            //attachment = excel;
            mail.Attachments.Add(excel);

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("brijesh.singh879@gmail.com", "*******");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

        }