gridview合并行列并导出Excel

这段代码演示了如何在.NET环境中,利用C#将一个带有合并单元格的GridView导出为Excel文件。通过MergeGridViewCell类合并网格视图的行和列,然后设置响应头以触发文件下载,确保内容类型为Excel应用,并解决数据导出时首字符'0'被过滤的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /// <summary>
        /// 导出合并的gridview
        /// </summary>
        /// <param name="dataSource">数据源</param>
        /// <param name="startColoum">要合并起始列,初始值:0</param>
        /// <param name="endColoum">要合并的结束列序号</param>
        /// <param name="filename">导出的文件名</param>
        /// <returns></returns>
        public virtual ActionResult ExportMergedGridViewToExcel(object dataSource, int startColoum, int endColoum, string filename = "excel")
        {
            GridView gv = new GridView();
            gv.DataSource = dataSource;
            gv.DataBind();
            MergeGridViewCell.MergeRow(gv, startColoum, endColoum);
            Response.ClearContent();
            Response.Clear();
            Response.Charset = "UTF8";
            Response.ContentEncoding = Encoding.UTF8;
          
            if (Request.Browser.Browser.ToLower() != "firefox")
            {
                filename = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(filename));
            }
            Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".xls"); Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            #region 解决数据第一个字符0导出被过滤掉的问题
         
            string strStyle = "<style>td{mso-number-format:\"\\@\";}</style>";
            sw.WriteLine(strStyle);
            #endregion
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            //gv.RenderControl(htw);
            //Response.Output.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sw.ToString());
            if (gv.Rows.Count > 0)
            {
                gv.RenderControl(htw);
                Response.Output.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sw.ToString());
            }
            Response.Flush();
            Response.End();

            return Content("");
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值