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

    直接贴上代码

        protected void BtnOutput_Click(object sender, EventArgs e)
        {
            this.GridView1.DataSourceID = SqlDataSource1.ID;
            Page.Response.Clear();
            //   防止中文内容为乱码     
            Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            //可令中文文件名不为乱码     
            Page.Response.AppendHeader("content-disposition""attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("LPC_Visitor_" + DateTime.Now.ToShortDateString(), System.Text.Encoding.UTF8) + ".xls\"");
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            this.GridView1.RenderControl(htw);
            Page.Response.Write(sw.ToString());
            Page.Response.End();
        }

    注:在你的代码里加入下面这个方法,方法里不用写任何东西

        public override void VerifyRenderingInServerForm(Control control)
        {
            //如果不加这个方法
            
    //运行报错类型“GridView”的控件“ctl00_ContentPlaceHolder1_GridView1”必须放在具有 runat=server 的窗体标记内。
        }

    注意事项:

    在导出的时候,如果某个字段为长数字(如身份证号码511922198507151512)、以0开头的编号(如0809111212)之类的数 据。如果不加处理在导出的Excel文件中将会被分别当作5.11922E+17和809111212来处理,这样与我们要达到 的实际效果不一致。所以我们要加以处理,即给单元格数据规定格式。常见的格式如下:

    1) 文本:vnd.ms-excel.numberformat:@
    2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
    3) 数字:vnd.ms-excel.numberformat:#,##0.00
    4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
    5) 百分比:vnd.ms-excel.numberformat: #0.00%

    使用方法如下:

    //给第一个单元格设置格式为

    e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");

    //给第四个单元格设置格式为

    e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");



     

  • 相关阅读:
    python字符串格式化 %操作符 {}操作符---总结
    Python中TKinter模块中的Label组件
    Python中urlopen()介绍
    Python中else语句块(和if、while、for、try搭配使用)
    Python文件操作汇总
    python socket 编程之三:长连接、短连接以及心跳
    python 源代码分析之调试设置
    python 调用shell或windows命令
    python socket 编程之二:tcp三次握手
    python socket 编程之一:编写socket的基本步骤
  • 原文地址:https://www.cnblogs.com/majunfeng/p/3933815.html
Copyright © 2011-2022 走看看