gpt4 book ai didi

c# - 在邮件中附加 excel 后检索空白 Excel

转载 作者:太空狗 更新时间:2023-10-29 23:38:15 25 4
gpt4 key购买 nike

我使用此代码从 gridview 发送带有 excel 附件的邮件,它对邮件部分工作正常,但 excel 附件始终为空白我已经调试了代码并确保 Gridview 的数据源传递了它需要的数据对于 gridview,似乎我没有将 gridview 渲染为 excel 正确。整个过程在 for each 循环中,具体取决于 foreach 中元素的数量..

我是否遗漏了一些代码?

protected void MailButton_Click(object sender, EventArgs e)
{
List<FOAM> foamList = new List<FOAM>(servs.GetAreaList());
foreach (FOAM foam in foamList)
{
Session["Area"] = foam.ItemAreaCode;
Session["Principal"] = foam.PrincipalAmount;
Session["Accountability"] = foam.AccountableAmount;
Session["Count"] = foam.ItemCount;

foamdetails.ItemAreaCode = foam.ItemAreaCode;
FOAMTemplateGridview.DataSource = servs.GetFoamAsOfUnsettledforAOM(foamdetails);
FOAMTemplateGridview.DataBind();

StringWriter _writer = new StringWriter();
HttpContext.Current.Server.Execute("AreaManagersMail.aspx", _writer);

StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
FOAMTemplateGridview.RenderControl(hw);

MailMessage newMail = new MailMessage();
newMail.Priority = MailPriority.High;
newMail.To.Add("test@test.com");
newMail.Subject = "Unsettled FOAM As of " + DateTime.Today.ToString("MMMM dd, yyyy") + "-A" + foam.ItemAreaCode;

System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);

newMail.Attachments.Add(new Attachment(mAtt, "test.xls"));
newMail.Body = _writer.ToString();
newMail.From = new MailAddress("test@test.com");
newMail.IsBodyHtml = true;
SmtpClient SmtpSender = new SmtpClient();
SmtpSender.Port = 25;
SmtpSender.Host = "MailHost";
SmtpSender.Send(newMail);

newMail.Dispose();
}


}

最佳答案

您得到的是空白 excel,因为您从 stw 中获取 bytes,它已定义但从未被赋予值。

stw is only a new object with no value that's why you are getting 0
bytes array
in mBArray.

比起你分配的 mAtt = new System.IO.MemoryStream(mBArray, false);。因此,mBArray 为空,mAtt 也为空,并且您从 mAtt 创建的文件为空,这就是您在电子邮件中收到空文件的原因。我想你需要改变这一行

byte[] mBArray = Enc.GetBytes(stw.ToString());

byte[] mBArray = Enc.GetBytes(_writer.ToString());

关于c# - 在邮件中附加 excel 后检索空白 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30663661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com