我知道我可以将我的gridview导出到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
将其作为附件发送到电子邮件中?
答案 0 :(得分:0)
将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
之后应该有一个填充的内存流答案 1 :(得分:0)
只需将字符串编写器中的数据拉出byte[]
,然后创建一个MemoryStream
传递字节数组数据,最后使用Attachements
MailMessage
集合} class将它附加到要发送的电子邮件,如下所示:
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.