ASP.NET - 将gridview数据导出为ex​​cel并直接发送邮件

时间:2012-07-03 09:47:23

标签: c# asp.net excel

我正在寻找一些示例编码,以便能够在每次启动页面时自动将当前gridview数据导出到excel文件,然后将其附加到邮件并发送邮件。

我有一个导出到excel函数,但是这个函数要求用户保存或查看文件,我非常需要跳过这一步,因为我希望我的脚本能够自动运行。

如果有人可以帮助我,我们将不胜感激:)

由于 凯文

2 个答案:

答案 0 :(得分:2)

尝试使用此代码

        string filename = "Test.xls"; 
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

        //Get the H`enter code here`TML for the control.
        yourGrid.RenderControl(hw);
        //Write the HTML back to the browser.
        Response.ContentType = "application/vnd.ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

        Response.Write(tw.ToString());

答案 1 :(得分:0)

首先,您必须将网格中的所有数据保存到Excel文件中。以下是如何将数据导出到Excel的示例。

http://zeeshanumardotnet.blogspot.com/2011/06/creating-reports-in-excel-2007-using.html

将数据导出到Excel文件后,您可以将其作为附件发送给任何收件人。有关如何发送附件的详细信息,请参阅此链接: -

http://www.codeproject.com/Articles/10828/Sending-Email-with-attachment-in-ASP-NET-using-SMT

因为您不希望用户按任何按钮,因此您可以在Page_load事件中编写这两个代码。