• 从DataGrid输出数据到Excel


    方法很简单,只是将DataGrid的内容输出到HtmlTextWriter流,再将流作为附件让用户下载或者用Excel打开.

    此方法虽然简单,但能实现功能.

    private void button_OutExcel_Click(object sender, System.EventArgs e)
      {
       Response.Clear();

        Response.Buffer= true;

        Response.Charset="utf-8";  

       this.EnableViewState = false;  

       //定义输入流
       System.IO.StringWriter writer = new System.IO.StringWriter();
       System.Web.UI.HtmlTextWriter txtwriter = new HtmlTextWriter(writer);
                //将DataGrid中的内容输出到txtwriter流中
       this.DataGrid1.RenderControl(txtwriter);

       //作为附件输出,filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm  

                Response.ContentType = "application/ms-excel"; //ContentType指定文件类型 可以为application/ms-excel    application/ms-word    application/ms-txt    application/ms-html    或其他浏览器可直接支持文档 

        Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls"); //下载

        //Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");  
       Response.Write(writer);
       Response.End();

      }

    ==================

    实例:

    //将DataGrid(dgBang)中的内容输出到Excel文件中,可以选择保存路径,并取名字
      private void GridToExcel_Click(object sender, System.EventArgs e)
      {
       Response.Clear(); //清除缓冲区流中的所有内容输出
       Response.Buffer= true; //
       Response.Charset="GB2312";    //设置输出流的http字符集
       //保存附件用"attachment;filename=bang.xls";在线打开用"online;filename=bang.xls"
       //可以是.doc、.xls、.txt、.htm、
       Response.AppendHeader("Content-Disposition","attachment;filename=bang.xls");
       Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
       //设置输出文件类型为excel文件。保存为word时,应为"application/ms-word"
       //可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html、或其他浏览器可直接支持文档 
       Response.ContentType = "application/ms-excel";
       this.EnableViewState = false;   //关闭保存视图状态
       System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);//区域设置
       System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
       System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
       this.dgBang.RenderControl(oHtmlTextWriter); //将DataGrid(dgBang)中的内容输出到oHtmlTextWriter
       Response.Write(oStringWriter.ToString());
       Response.End();//将当前所有缓冲的输出发送到客户端,并停止该页执行

      }

    实例GridView2excel
    详细见附件:/Files/chenlong/GridView2excel.rar

  • 相关阅读:
    c 概念详解
    c 目录
    win文件操作
    使用panads处理数据
    冒泡排序
    notepad++搭建python环境
    继承方法-->一级一级继承
    原型问题2—原型对象的替换
    原型问题1—原型对象的替换
    js继承——扩展Object方式实现继承
  • 原文地址:https://www.cnblogs.com/chenlong/p/1600681.html
Copyright © 2020-2023  润新知