zoukankan      html  css  js  c++  java
  • ASP.NETGridView导出excle

    public void ExportToExcel(Page myPage, GridView ctl, string filename)
    {
    //ctl.BottomPagerRow.Visible = false;//导出到Excel表后,隐藏分页部分

    ctl.Columns[0].Visible = false;//隐藏“编辑”列

    //ctl.AllowPaging = false;//取消分页,便于导出所有数据,不然只能导出当前页面的几条数据

    //DataView dv = getDt().DefaultView;
    //ctl.DataSource = dv;
    //ctl.DataBind();
    /*
    foreach (GridViewRow dg in this.gdvSort.Rows)
    {
    dg.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
    dg.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
    dg.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
    dg.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
    }
    */
    HttpResponse Response;
    Response = myPage.Response;
    foreach (TableCell tc in ctl.HeaderRow.Cells)
    {
    // TableCell里的每个Control
    foreach (Control c in tc.Controls)
    {
    // 如果控件继承自接口IButtonControl
    if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
    {
    // 如果该控件不是“导出Excel”按钮则把button转换成文本
    tc.Controls.Clear();
    tc.Text = ((IButtonControl)c).Text;
    }
    }
    }

    bool CurrCtlVisible = ctl.Visible;
    ctl.Visible = true;
    Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Response.ContentType = "application/ms-excel";
    ctl.Page.EnableViewState = false;
    System.IO.StringWriter tw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
    ctl.RenderControl(hw);
    Response.Write(tw.ToString());
    Response.End();
    ctl.Page.EnableViewState = true;
    ctl.Visible = CurrCtlVisible;
    }

    //////////////////

    // 隐藏指定的列
    if (hideColumns != null)
    {
    foreach (int columnIndex in hideColumns)
    {
    if (columnIndex < gridView.Columns.Count)
    {
    gridView.Columns[columnIndex].Visible = false;
    }
    }
    }

    // 如果HeaderRow里的控件是button的话,则把它替换成文本
    foreach (TableCell tc in gridView.HeaderRow.Cells)
    {
    // TableCell里的每个Control
    foreach (Control c in tc.Controls)
    {
    // 如果控件继承自接口IButtonControl
    if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
    {
    // 如果该控件不是“导出Excel”按钮则把button转换成文本
    tc.Controls.Clear();
    tc.Text = ((IButtonControl)c).Text;
    }
    }
    }

  • 相关阅读:
    asp.net Post Get提交数据转Model实例
    ETL构建数据仓库五步法
    什么是数据仓库-数据仓库的基本概念
    简单的说下什么是数据仓库
    简单理解Socket
    Net中的反射使用入门
    JS---BOM
    jQuery Ajax 全解析
    Ajax与JSON的一些总结
    ASP.NET中验证控件的使用
  • 原文地址:https://www.cnblogs.com/zyh-C/p/9949289.html
Copyright © 2011-2022 走看看