如何发送的GridView为Excel电子邮件附件 [英] How do I send gridview as excel email attachment

查看:129
本文介绍了如何发送的GridView为Excel电子邮件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以导出我的GridView控件,而无需使用 VerifyRenderingInServerForm(控制控制)创先争优是这样的:

I know I can export my gridview to excel without using VerifyRenderingInServerForm(Control control) like this:

 Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition",
         "attachment;filename=filename.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.AllowPaging = false;
        GridView1.DataBind();

        //Change the Header Row back to white color
        GridView1.HeaderRow.Style.Add("background-color", "#003c74");
        GridView1.HeaderRow.Style.Add("color", "#ffffff");

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");

            //Apply style to Individual Cells of Alternating Row
            if (i % 2 != 0)
            {
                row.BackColor = System.Drawing.Color.AliceBlue;
            }
        }
        GridView1.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

我如何修改此使用内存流,以便在电子邮件中作为附件发送吗?

How do I modify this to use the Memory Stream in order to send this in an email as an attachment?

推荐答案

只要把数据从被串作家成字节[] ,然后创建一个的MemoryStream 传递给它的字节数组数据,最后使用附着物的集合 MAILMESSAGE 类,它附加到电子邮件发送,就像这样:

Just pull the data out of the string writer into a byte[] and then create a MemoryStream passing it the byte array data, finally use the Attachements collection of the MailMessage class to attach it to the email to send, like this:

MailMessage mail = new MailMessage();

System.Text.Encoding theEncoding = System.Text.Encoding.ASCII;
byte[] theByteArray = theEncoding.GetBytes(sw.ToString());
MemoryStream theMemoryStream = new MemoryStream(theByteArray, false);
mail.Attachments.Add(new Attachment(theMemoryStream, "YOUR_FILE_NAME.xls"));

// Do remainder of your email settings here, To, From, Subject, etc.

这篇关于如何发送的GridView为Excel电子邮件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆