(1)StringWriter 不能用,因为没有引入命名空间System.IO
(2)Encoding不能用,因为没有引入命名空间System.Text
(3)在用户控件上使用的GridView不能重写VerifyRenderingInServerForm函数。
一、GridView数据导出到Excel文件中
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getDataSet();
GridView1.DataBind();
}
}
//filename为Excel的名字,ToExcelGrid就是数据源,在此为DataView数据源;
private void ExportExcelFromDataGrid(string filename, System.Web.UI.WebControls.GridView ToExcelGrid)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
ToExcelGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
//如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内ITPUB个人空间 cB6w"i'J/n
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
//里边不写任何的东西
}
protected void btnWrite_Click(object sender, EventArgs e)
{
ExportExcelFromDataGrid("TestExcel.xls", this.GridView1);
}
}
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛