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

  • 相关阅读:
    python PIL实现图片合成
    pycharm在windows中如何安装dlib?
    Git将文件上传至Github过程
    安装skimage和cv2
    ubuntu下pip的安装,更新及卸载
    pycharm专业版激活破解(亲测有效)
    docker部署tensorflow serving以及模型替换
    Keras在MNIST实现LeNet-5模型训练时的错误?
    Ubuntu中VMware tools的安装步骤
    win10执行Tensorflow,总是会报错“DLL load failed: 找不到指定的模块”的解决方式----终极版方式
  • 原文地址:https://www.cnblogs.com/Teddy/p/534078.html
Copyright © 2011-2022 走看看