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"。

  • 相关阅读:
    js对象方法
    重要的小知识点
    vs2017引用vue组件中文乱码
    单行文本溢出打点、多行文本溢出打点
    span和input布局时对不齐
    在思科三层交换机上配置DHCP,不同网段/VLAN间互通
    搭建ssm整合
    使用Redis
    MyBatis常用实现方式
    Java 面向对象
  • 原文地址:https://www.cnblogs.com/Teddy/p/534078.html
Copyright © 2011-2022 走看看