http://www.cnblogs.com/sanshi/archive/2009/08/23/1552533.html

解决方案 »

  1.   

    你试试 将GridPanel中的数据现在添加到一个DataTable里面 
      for (int i = 0; i < this.GridPanel.Columns.Count; i++)
                {
                    //将表头信息添加到DataTable表头 
                    dt2.Columns.Add(this.GridPanel.Columns[i].HeaderText);            }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                        dt2.Rows.Add(dt.Rows[i].ItemArray);  //添加数据行
                }
                ToExcel(dt2);
    然后在
    public void ToExcel(DataTable dt)
            {
                DataGrid dgExcel = new DataGrid();
                dgExcel.DataSource = dt;
                dgExcel.DataBind();
                HttpContext.Current.Response.Charset = "GB2312";
                string fileName = HttpUtility.UrlEncode(Guid.NewGuid().ToString(), System.Text.Encoding.UTF8);
                string str = "attachment;filename=" + fileName + ".xls";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.AppendHeader("content-disposition", str);
                StringWriter sw = new StringWriter();
                HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
                dgExcel.RenderControl(htmTextWriter);
                HttpContext.Current.Response.Write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
                string style = "<style>td{mso-number-format:\"\\@\";}</style>";//防止导出excel时将以0开头的全数字数据的0去掉 
                HttpContext.Current.Response.Write(style);
                HttpContext.Current.Response.Write("</head><body>");
                HttpContext.Current.Response.Write(sw);
                HttpContext.Current.Response.Write("</body></html>");
                HttpContext.Current.Response.End();
            }