GridView导出到EXCEL

这个是老生常谈了,网上有很多博文介绍。这里自己也写下来方便以后查看。

先贴代码

public static void ExportGridView(GridView gv, string fileName)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                GridViewRow row = gv.Rows[i];                
                row.Cells[0].Attributes.Add("class", "textmode");
            }
            
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            string style = @"<style> .textmode { mso-number-format:\#; } </style>";
            HttpContext.Current.Response.Write(style);
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }


 

说明:

1,导出的是.xls的,暂时没找到导出.xlsx的。以后找到再记。

string attachment = "attachment; filename=" + fileName + ".xlsx";

HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

没有解决问题,导出的文件打不开。

2,fileName如果包含中文,在IE下导出后会是乱码。需要编码。

 

3,如果导出的某一行的数字显示成“1.222E+11”的形式,可以添加样式{ mso-number-format:\#; }。

遍历GridView的行

GridViewRow row = gv.Rows[i];                               

给每一行的单元格添加样式。

row.Cells[0].Attributes.Add("class", "textmode");

 

4,需要重写事件,否则会报错,说“GridView 需要放在runat=server的容器里”。

 

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
        }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值