如何将gridview作为excel电子邮件附件发送



我知道我可以将我的网格视图导出到excel,而无需像这样使用VerifyRenderingInServerForm(Control control)

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

如何将其修改为使用Memory Stream,以便将其作为附件发送到电子邮件中?

只需将字符串写入程序中的数据拉入byte[],然后创建一个MemoryStream,将字节数组数据传递给它,最后使用MailMessage类的Attachements集合将其附加到要发送的电子邮件中,如下所示:

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.

将StringWriter更改为StreamWriter并向其中传递MemoryStream。因此,更改以下内容:

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

收件人:

MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
HtmlTextWriter hw = new HtmlTextWriter(sw);

然后,在调用GridView之后,应该有一个填充的内存流。RendControl

最新更新