table,gridview 导出Excel

public void OutPutExcel()
        
{
            
//定义文档类型、字符编码
            Response.Clear();
          Response.Buffer
= true;
          Response.Charset
="GB2312";
            
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
          
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm
          Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
          Response.ContentEncoding
=System.Text.Encoding.GetEncoding("GB2312");
          
//Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
          Response.ContentType = "application/ms-excel";
          
this.EnableViewState = false;
            
// 定义一个输入流
          System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
          System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);

            
this.RenderControl(oHtmlTextWriter);
          
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
          Response.Write(oStringWriter.ToString());
          Response.End();
        }

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

 


    /// <summary>
    /// 将整个页面数据导入EXCEL
    /// </summary>
    public  void TableDataToExcel()
    {
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=导出文件.xls");
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.ContentType = "application/octet-stream";      
    }

    /// <summary>
    /// 将GridView分页数据导入EXCEL
    /// </summary>
    /// <param name="myGridView">GridView名称ID </param>
    public  void GridViewToExcel(System.Web.UI.WebControls.GridView myGridView)
    {
        for (int i = 0; i < myGridView.Columns.Count; i++)
        {
            myGridView.Columns[i].ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            for (int u = 0; u < myGridView.Rows.Count; u++)
                myGridView.Rows[u].Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
        }
        StringWriter stringWrite = new System.IO.StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        HttpContext.Current.Response.Clear();       
        //HttpContext.Current.Response.Charset = "UTF-8";
        //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;

        HttpContext.Current.Response.Charset = "gb2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;  //使用UTF7无乱码
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=file.xls");

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //HttpContext.Current.Response.ContentType = "application/octet-stream";
        ////HttpContext.Current.Response.ContentType = "application/vnd.xls";

        //预防出现控件必须放在具有 runat=server 的窗体标记内的错误
        Page page = new Page();
        HtmlForm form = new HtmlForm();
        myGridView.EnableViewState = false;
        // Deshabilitar la validación de eventos, sólo asp.net 2
        page.EnableEventValidation = false;
        // Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
        page.DesignerInitialize();
        page.Controls.Add(form);
        form.Controls.Add(myGridView);
        page.RenderControl(htmlWrite);

        //myGridView.RenderControl(htmlWrite);
        HttpContext.Current.Response.Write(stringWrite.ToString());
        HttpContext.Current.Response.End();      
      
    }

  
    /// <summary>
    /// 将这个gridview 数据源里的数据全部导出到exel
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="dts"></param>
    /// <param name="sql"></param>
    public void OutputGridViewAll(GridView gv, DataTable dts, string sql)
    {
        DataTable dt = null;
        if (sql.Trim() != "")
        {
            dt = clsData.ExecDataTable(sql);
            gv.DataSource = dt;
            gv.DataBind();
        }
        else
        {
            gv.DataSource = dts;
            gv.DataBind();
        }
        for (int i = 0; i < gv.Columns.Count; i++)
        {
            gv.Columns[i].ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            for (int u = 0; u < gv.Rows.Count; u++)
                gv.Rows[u].Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
        }

        //string style = @"<style> .text { mso-number-format:\@; } </script> ";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);


        HttpContext.Current.Response.Clear(); 
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
        //HttpContext.Current.Response.Write("<meta   http-equiv=Content-Type   content=text/html;charset=GB2312>");
        string ExcelFileName = "file.xls";
        //string fileName = HttpUtility.UrlEncode(ExcelFileName + ".xls", Encoding.GetEncoding("GB2312"));
        //HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + ExcelFileName);
       HttpContext.Current.Response.ContentType = "application/ms-excel";
       HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(ExcelFileName));
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //this.EnableViewState = false;


        //预防出现控件必须放在具有 runat=server 的窗体标记内的错误
        Page page = new Page();
        HtmlForm form = new HtmlForm();
        gv.EnableViewState = false;
        // Deshabilitar la validación de eventos, sólo asp.net 2
        page.EnableEventValidation = false;
        // Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
        page.DesignerInitialize();
        page.Controls.Add(form);
        form.Controls.Add(gv);
        page.RenderControl(htw);

      
     

        //gv.RenderControl(htw);
        // Style is added dynamically
        //Response.Write(style);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// 将页面Table数据存入EXCEL
    /// </summary>
    /// <param name="p1">放Table的Panel容器的ID</param>
    public void OutputGridView(Panel p1)
    {      

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        //预防出现控件必须放在具有 runat=server 的窗体标记内的错误
        Page page = new Page();
        HtmlForm form = new HtmlForm();
        //gv.EnableViewState = false;
        // Deshabilitar la validación de eventos, sólo asp.net 2
        page.EnableEventValidation = false;
        // Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
        page.DesignerInitialize();
        page.Controls.Add(form);
        //form.Controls.Add(gv);
        p1.RenderControl(htw);


        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ContentType = "application/excel";
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        //HttpContext.Current.Response.Write("<meta   http-equiv=Content-Type   content=text/html;charset=GB2312>");
        string ExcelFileName = "file.xls";
        //string fileName = HttpUtility.UrlEncode(ExcelFileName + ".xls", Encoding.GetEncoding("GB2312"));
        //HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + ExcelFileName);
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(ExcelFileName));
     

        //gv.RenderControl(htw);
        // Style is added dynamically
        //Response.Write(style);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();
    }

posted @ 2008-12-03 11:41  城市里的鱼  阅读(881)  评论(0)    收藏  举报