后台代码
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="excelName"></param>
/// <param name="html"></param>
/// <param name="cssName"></param>
public static void OutExcel(string excelName, string html, string cssName)
{
using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(string.Format("../style/form/{0}", cssName)), Encoding.UTF8))
{
cssName = sr.ReadToEnd();
sr.Close();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + excelName + ".xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">");
HttpContext.Current.Response.Write("<meta name=ProgId content=Excel.Sheet>");
HttpContext.Current.Response.Write("<meta name=Generator content=\"Microsoft Excel 11\">");
HttpContext.Current.Response.Write("<style>");
HttpContext.Current.Response.Write(cssName);
HttpContext.Current.Response.Write("</style>");
HttpContext.Current.Response.Write("<!--[if gte mso 9]>");
HttpContext.Current.Response.Write("<xml>");
HttpContext.Current.Response.Write(" <x:ExcelWorkbook>");
HttpContext.Current.Response.Write(" <x:ExcelWorksheets>");
HttpContext.Current.Response.Write(" <x:ExcelWorksheet>");
HttpContext.Current.Response.Write(string.Format(" <x:Name>{0}</x:Name>", excelName));
HttpContext.Current.Response.Write(" <x:WorksheetOptions>");
HttpContext.Current.Response.Write(" <x:Print>");
HttpContext.Current.Response.Write(" <x:ValidPrinterInfo />");
HttpContext.Current.Response.Write(" <x:PaperSizeIndex>9</x:PaperSizeIndex>");//打印A4纸
HttpContext.Current.Response.Write(" </x:Print>");
HttpContext.Current.Response.Write(" </x:WorksheetOptions>");
HttpContext.Current.Response.Write(" </x:ExcelWorksheet>");
HttpContext.Current.Response.Write(" </x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]-->");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write("<body>");
HttpContext.Current.Response.Write(html);
HttpContext.Current.Response.Write("</body></html>");
HttpContext.Current.Response.End();
}
//页面存放控件
<p id="tbForm">
<!=页面要到导出的内容->
</p>
<asp:Button Text="导出Excel" CssClass="butBase" ID="btnExcel" runat="server" UseSubmitBehavior="false" onclick="btnExcel_Click" OnClientClick="$('#hfHtml').val($('#tbForm').html())"/>
<asp:HiddenField ID="hfHtml" runat="server" />