public static void GridViewToExcel(GridView grd, HttpResponse response, string charset) {

            RemoveControls(grd);

            response.Clear();

            response.Buffer = true;

            response.Charset = charset;

            response.AppendHeader("Content-Disposition", "attachment;filename=NewFileName.xls"); //文件名可以自定义

            response.ContentEncoding = System.Text.Encoding.UTF8;

            response.ContentType = "application/ms-excel";

 

            System.Globalization.CultureInfo AreaInfo = new System.Globalization.CultureInfo("zh-CN", true);

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(AreaInfo);

            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

    //可选:定义样式

            oStringWriter.WriteLine(Styles());

           

            grd.GridLines = GridLines.Both;

            grd.Font.Name = "Arial";

            grd.HeaderStyle.Font.Bold = true;

            grd.RenderControl(oHtmlTextWriter);

            response.Write(oStringWriter.ToString());

            response.End();

        }

        //样式可以在EXCEL中设置好后,另存为HTML来确定

    private static string Styles(){

    return "<style>td{mso-number-format:\"\\@\";}.dateTime{mso-number-format:\"h\\:mm\"}</style>";

    }

   //如GridView的CheckBox,Button,TextBox等等

        private static void RemoveControls(Control gv)

        {

            Literal replace = new Literal();

            for (int i = 0; i < gv.Controls.Count; i++){

                if (gv.Controls[i].GetType() == typeof(CheckBox)){

       replace.Text = ((CheckBox)gv.Controls[i]).Checked ? "Y" : "N";

                    gv.Controls.Remove(gv.Controls[i]);

                    gv.Controls.AddAt(i, replace);

                }

                if (gv.Controls[i].HasControls()){

                    RemoveControls(gv.Controls[i]);

                }

            }

        }

 

相关文章:

  • 2021-11-10
  • 2022-12-23
  • 2021-09-26
  • 2022-01-03
  • 2021-12-08
  • 2021-07-06
  • 2021-06-23
猜你喜欢
  • 2021-07-30
  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2022-02-02
  • 2022-12-23
相关资源
相似解决方案