ExportExcel.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Web;
  3. using System.Web.UI;
  4. using System.IO;
  5. using System.Web.UI.WebControls;
  6. namespace Ant.Service.Utilities
  7. {
  8. public class ExportExcel
  9. {
  10. protected void ExportData(string strContent, string FileName)
  11. {
  12. FileName = FileName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
  13. HttpContext.Current.Response.Clear();
  14. HttpContext.Current.Response.Charset = "gb2312";
  15. HttpContext.Current.Response.ContentType = "application/ms-excel";
  16. HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
  17. //this.Page.EnableViewState = false;
  18. // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
  19. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
  20. // 把文件流发送到客户端
  21. HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
  22. HttpContext.Current.Response.Write(strContent);
  23. HttpContext.Current.Response.Write("</body></html>");
  24. // 停止页面的执行
  25. //Response.End();
  26. }
  27. /// <summary>
  28. /// 导出Excel
  29. /// </summary>
  30. /// <param name="obj"></param>
  31. public void ExportData(GridView obj)
  32. {
  33. try
  34. {
  35. string style = "";
  36. if (obj.Rows.Count > 0)
  37. {
  38. style = @"<style> .text { mso-number-format:\@; } </script> ";
  39. }
  40. else
  41. {
  42. style = "no data.";
  43. }
  44. HttpContext.Current.Response.ClearContent();
  45. DateTime dt = DateTime.Now;
  46. string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
  47. HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportData" + filename + ".xls");
  48. HttpContext.Current.Response.ContentType = "application/ms-excel";
  49. HttpContext.Current.Response.Charset = "GB2312";
  50. HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  51. StringWriter sw = new StringWriter();
  52. HtmlTextWriter htw = new HtmlTextWriter(sw);
  53. obj.RenderControl(htw);
  54. HttpContext.Current.Response.Write(style);
  55. HttpContext.Current.Response.Write(sw.ToString());
  56. HttpContext.Current.Response.End();
  57. }
  58. catch
  59. {
  60. }
  61. }
  62. }
  63. }