zoukankan      html  css  js  c++  java
  • GridView导出Excel

            为了完成领导交代的任务,这几天都在做数据展现,因为时间比较紧,所以也没做太复杂,使用GridView来展示数据库表。几乎没对GridView的格式做什么设定,从配置文件中加载SQL,跑出数据就直接绑定到GridView。发现了一些问题,比如GridView的自动绑定列的宽度是没法设定的,而此时GridView的表格输出是不带宽度信息的,所以导致表格列比较多的时候显示起来会挤到页面里面很难看,由于表的列数并不是固定的,所以也没法很简单的用模版列的方式做,最后只好直接将表格宽度设置成一个很大的数了事。。。
            此外做了个导出Excel的功能,主要代码如下:
     1        private void DumpExcel(GridView gv, string FileName)
     2        {//带格式导出
     3            string style = @"<style> .text { mso-number-format:\@; } </script>";
     4            Response.ClearContent();
     5            Response.Charset = "GB2312";
     6            Response.ContentEncoding = System.Text.Encoding.UTF8;
     7            Response.AddHeader("content-disposition""attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
     8            Response.ContentType = "application/excel";
     9            StringWriter sw = new StringWriter();
    10            HtmlTextWriter htw = new HtmlTextWriter(sw);
    11            gv.RenderControl(htw);
    12            // Style is added dynamically
    13            Response.Write(style);
    14            Response.Write(sw.ToString());
    15            Response.End();
    16        }

    17        public override void VerifyRenderingInServerForm(Control control)
    18        {
    19        }

    20
            上面的行17的重载函数是必须的,否则会报“GridView要在有run=server的From体内”的错。
            此外,变量style的作用是控制GridView列的样式,避免发生excel表中字符前导0被当成数字给截掉这样的问题, 通过Response.Write方法将其添加到输出流中。最后把样式添加到ID列。这一步需要在RowDataBound事件中完成:
    1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    2
    3if (e.Row.RowType == DataControlRowType.DataRow)
    4{
    5e.Row.Cells[1].Attributes.Add("class""text"); 
    6}

    7}
  • 相关阅读:
    文件下载链接
    Python Web服务器
    打印字符串替换
    python 将数据写入excel
    python Telnet通讯
    Python 串口通讯
    monkey 原理,环境搭建、命令详解
    Andriod 四大组件,六大布局
    python练习题100例
    Activity的基本概念与Activity的生命周期
  • 原文地址:https://www.cnblogs.com/badwood316/p/1051344.html
Copyright © 2011-2022 走看看