页面的GridView,导到Excel
aspx页面:
<%@ Page EnableEventValidation="false"%>
.cs页面
//导出到excel
protected void btnexport_Click(object sender, EventArgs e)
{
/GridView的设置
GridViewSet();
Export("application/ms-excel", "*****报表.xls");
}
private void GridViewSet()
{
//将不需要的列设置为不可见,如编辑删除列等
this.GVcategoryList.Columns["不需要的列的索引号"].Visible = false;
//将允许分页设置为false,在此绑定数据
this.GVcategoryList.AllowPaging = false;
this.BindGvList();
}
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GVcategoryList.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
//下面这句很必要,不然会出错,出错信息为: 类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
public override void VerifyRenderingInServerForm(Control control)
{
}
在导到office2003Excel上时没有问题的,但是导出到2007就会出现问题了?有遇到过这样问题的朋友可以和我交流下。