
























PrepareGridViewForExport(Control gv)//将模版列显示出来
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
this.GridView1.AllowPaging = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.GridView1.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
//Response.Write(dt.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)

...{
//在后台中重载VerifyRenderingInServerForm()方法,否则报错为“类型"GridView"的控件"GridView1"必须放在具有 runat=server 的窗体标记内“
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

...{
if (e.Row.RowType == DataControlRowType.DataRow)

...{
e.Row.Cells[3].Attributes.Add("class", "text");//在数字列前存在的 0 的列中加入 class 样式 以便保存 0
}
}

注:如果GricView中有分页的话,导出到Excel时就会报错.可通过修改页文件可以修正这个问题:EnableEventValidation = "false".

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

如果GridView存在模板列,其中包含子控件,例如CheckBox等,导出EXCEL后就会出现该区域的不规律。所以要对模板列单独处理(转载)
private void PrepareGridViewForExport(Control gv)//模式化特殊元素 flashcong

...{

LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;

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

...{

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

...{

l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

...{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);

}

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

...{

l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(ImageButton))

...{
l.Text = "图片";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}

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

...{
PrepareGridViewForExport(gv.Controls[i]);
}

}

}对以上特殊元素,可以替换成目标代码输出即可

































































































