private void toexcel(string title)
{
Response.Clear();
Response.Buffer = false;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(title) + ".xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);// 数字字符导Excel后转Text格式,否则前面的 0 字符会自动舍弃
Response.Write(AddExcelHead());
Response.Write(oStringWriter.ToString());
Response.Write(AddExcelbottom());
Response.End();
}
protected void btn_toexcel_Click(object sender, EventArgs e)
{
toexcel("订单详细");
}
public static string AddExcelHead()
{
StringBuilder sb = new StringBuilder();
sb.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
sb.Append(" <head>");
sb.Append(" <!--[if gte mso 9]><xml>");
sb.Append("<x:ExcelWorkbook>");
sb.Append("<x:ExcelWorksheets>");
sb.Append("<x:ExcelWorksheet>");
sb.Append("<x:Name></x:Name>");
sb.Append("<x:WorksheetOptions>");
sb.Append("<x:Print>");
sb.Append("<x:ValidPrinterInfo />");
sb.Append(" </x:Print>");
sb.Append("</x:WorksheetOptions>");
sb.Append("</x:ExcelWorksheet>");
sb.Append("</x:ExcelWorksheets>");
sb.Append("</x:ExcelWorkbook>");
sb.Append("</xml>");
sb.Append("<![endif]-->");
sb.Append(" </head>");
sb.Append("<body>");
return sb.ToString();
}
public static string AddExcelbottom()
{
StringBuilder sb = new StringBuilder();
sb.Append("</body>");
sb.Append("</html>");
return sb.ToString();
}
//重新下面方法解决错误:类型GridView的控件GridView1必须放置在具有runat=server的窗体标记内
public override void VerifyRenderingInServerForm(Control control)
{
}