在我的应用程序中,我有一个用于下载excel文件的按钮..
OnButtonClick代码:
protected void btnmacdesc_Click(object sender, EventArgs e)
{
if (fileName_macdesc.Length > 0)
{
fileName_macdesc.Remove(0, fileName_macdesc.Length);
}
fileName_macdesc = "daily_macdesc_" + DateTime.Now.ToString("ddMMMyyyyhhmm") + ".xls";
try
{
DataSet ds_macdesc = (DataSet)Session["sessionmachinedesc_ds"];
gv.DataSource = ds_macdesc.Tables[0];
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName_macdesc));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table table = new Table();
gv.GridLines = GridLines.Both;
table.GridLines = gv.GridLines;
if (gv.HeaderRow != null)
{
PrepareGridViewForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
for (int k = 0; k < ds_macdesc.Tables[0].Columns.Count; k++)
{
table.Rows[0].Cells[k].BackColor = gv.HeaderStyle.BackColor;
table.Rows[0].Cells[k].ForeColor = gv.HeaderStyle.ForeColor;
table.Rows[0].Cells[k].Font.Bold = true;
}
}
foreach (GridViewRow row in gv.Rows)
{
PrepareGridViewForExport(row);
table.Rows.Add(row);
}
if (gv.FooterRow != null)
{
PrepareGridViewForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
bool altColor = false;
for (int i = 1; i < table.Rows.Count; i++)
{
if (!altColor)
{
for (int kl = 0; kl < ds_macdesc.Tables[0].Columns.Count; kl++)
{
table.Rows[i].Cells[kl].BackColor = gv.RowStyle.BackColor;
}
altColor = true;
}
else
{
for (int lk = 0; lk < ds_macdesc.Tables[0].Columns.Count; lk++)
{
table.Rows[i].Cells[lk].BackColor = gv.AlternatingRowStyle.BackColor;
}
altColor = false;
}
}
table.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
//HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
// send_mail_daily(fileName_macdesc);
}
}
}
catch (Exception ex)
{
CreateLogFiles Err = new CreateLogFiles();
Err.ErrorLog(Server.MapPath("../Logs/ErrorLog"), ex.Message, "Admin_admin_dailyreport==>btnmacdesc_Click");
}
}
我可以毫无问题地下载excel文件。现在,他们要求我通过相同的按钮点击将下载的文件作为附件发送到电子邮件中。是否可以这样做?
所以我试着在按钮事件的最后一行调用一个函数(send_mail_daily),但是我无法附加它。执行最后一行后,将显示“另存为”对话框选项。请指导我解决这个问题,还是有其他替代解决方案。
功能代码:
public void send_mail_daily(string filename)
{
MailMessage mail = new MailMessage();
mail.To = "abc@in.bIZ";
mail.From = "abc@in.BIZ";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body.";
MailAttachment attachment = new MailAttachment(Server.MapPath(filename.ToString())); //create the attachment
mail.Attachments.Add(attachment); //add the attachment
SmtpMail.SmtpServer = "abc.in.def.LOCAL"; //your real server goes here
SmtpMail.Send(mail);
}
答案 0 :(得分:1)
在CompleteRequest之前尝试send_mail_daily。
只要您在正确的位置获得代码,就没有理由不能这样做。