将gridview数据导入到Exccl里

来源:百度文库 编辑:神马文学网 时间:2024/04/28 23:37:00
///
///这是导入方法
///
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 必须放在runat=server的控件里
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
//里边不写任何的东西
}
///
/// 到入按钮2
///

///
///
protected void btn_Click(object sender, EventArgs e)
{
ExportExcelFromDataGrid("TestExcel.xls", this.GridView1);
}