2013-12-09 80 views
-1

我知道我可以導出我的GridView到Excel,而無需使用VerifyRenderingInServerForm(Control control)這樣的:如何發送的GridView爲Excel電子郵件附件

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

只要把數據從串作家成一個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. 
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