首页 > 其他 > 详细

将GridView中的数据导出到Excel代码与注意事项

时间:2016-04-07 13:13:40      阅读:302      评论:0      收藏:0      [点我收藏+]
//gv:需要导出数据的GridView,filename:导出excel文件名
public void ExportToExcel(GridView gv, string filename) { string style = @"<style> .text { mso-number-format:\@; } </style> "; Response.ClearContent(); HttpContext.Current.Response.Charset = "UTF8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;//注意编码 Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.PageSize = Int16.MaxValue;
//导出之前一定要再次绑定数据源,不然导出无数据 gv.DataSource = getGridViewData(); gv.DataBind(); gv.RenderControl(htw); // Style is added dynamically Response.Write(style); Response.Write(sw.ToString()); Response.End(); }
//必须加上这个函数,函数中没有任何内容只是重载一下,不然会报错:... type ‘GridView‘ must be placed inside a form tag with runat=server. public override void VerifyRenderingInServerForm(Control control) { }
//可以在每行数据绑定的时候设置数据格式
   protected void IBDetailGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex > -1)
        {
            e.Row.Cells[7].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Row.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat:@");           
        }
    }

  

将GridView中的数据导出到Excel代码与注意事项

原文:http://www.cnblogs.com/wen20104659/p/5362926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!