public virtual ActionResult ExportToExcel(object dataSource, string filename = "excel")
{
GridView gv = new GridView();
gv.DataSource = dataSource;
gv.DataBind();
Response.ClearContent();
Response.Clear();
Response.Charset = "UTF8";
Response.ContentEncoding = Encoding.UTF8;
if (Request.Browser.Browser.ToLower() != "firefox")
{
filename = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(filename));
}
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".xls"); Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
//解决导出第一个0被过滤掉
string strStyle = "<style>td{mso-number-format:\"\\@\";}</style>";
sw.WriteLine(strStyle);
HtmlTextWriter htw = new HtmlTextWriter(sw);
if (gv.Rows.Count > 0)
{
gv.RenderControl(htw);
Response.Output.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sw.ToString());
}
Response.Flush();
Response.End();
return Content("");
}