码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-04-07 13:13:56      阅读:109      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!