zoukankan      html  css  js  c++  java
  • 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"。

  • 相关阅读:
    eclipse internal web browser 不可用在linux下的解决
    Asp.Net MVC4入门指南(10):第三方控件Studio for ASP.NET Wijmo MVC4 工具应用
    生成树计数MatrixTree定理
    strcpy与strncpy
    [置顶] 游戏开发技术总结(经典之作)第七集 广阔天地游戏大地图的形成方法的地图移动
    Inside COM接口
    UTC时区表(.Net)
    java练习
    如果Imageview与Linearlayout有叠加且可选资源长度不同,如何布局?
    【Android测试】Android抓包解析全过程
  • 原文地址:https://www.cnblogs.com/Teddy/p/534078.html
Copyright © 2011-2022 走看看