Asp.net中导出成Excel等格式

我们做一个测试程序:
1、在空白页上创建一个GridView,给它指定一个数据源,填充一些测试数据(此例中是GridView1)。
2、给页面添加一个按钮(此例中是btnExport),在按钮的单击事件中填入如下代码:
protected void btnExport_Click(object sender, EventArgs e)
{
        Response.Clear();
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
        Response.AppendHeader("content-disposition", "attachment;filename=\"" + HttpUtility.UrlEncode("[" + DateTime.Now.ToString("yyyy-MM-dd") + "]", System.Text.Encoding.UTF8) + ".xls\"");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        // If you want the option to open the Excel file without saving then
        // comment out the line below
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
}
3、重载方法VerifyRenderingInServerForm,否则VS编译器报错。
public override void VerifyRenderingInServerForm(Control control)
{
}
4、运行页面,单击按钮,弹出提示框,要你选择保存或打开一个以当前时间命名的Excel文件。

注意事项:若表格中有中文必须将编码格式设置为gb2312,如下:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
必须重载VerifyRenderingInServerForm方法。
还可以导出成各种形式的文档,只需把Response.ContentType的值设置成别的就可以,具体值可以从网上查到,如要导出成Word格式可以将Response.ContentType的值设置成"application/word.doc"。

posted @ 2006-10-19 20:41  Teddy  阅读(891)  评论(1编辑  收藏  举报