XLSHelper.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Data;
  3. using System.Text;
  4. using System.Web;
  5. namespace iNethinkCMS.Helper
  6. {
  7. public class XLSHelper
  8. {
  9. public static void DataTableExportExcel(DataTable dt, string FileName)
  10. {
  11. HttpContext current = HttpContext.Current;
  12. current.Response.Clear();
  13. current.Response.Charset = "UTF-8";
  14. current.Response.Buffer = true;
  15. current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
  16. current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(FileName, Encoding.UTF8) + ".xls\"");
  17. current.Response.ContentType = "application/vnd.ms-excel";
  18. foreach (DataColumn dataColumn in dt.Columns)
  19. {
  20. current.Response.Output.Write(dataColumn.ColumnName.ToString().Trim() + "\t");
  21. }
  22. current.Response.Output.Write("\n");
  23. foreach (DataRow dataRow in dt.Rows)
  24. {
  25. string text = "";
  26. for (int i = 0; i < dt.Columns.Count; i++)
  27. {
  28. text = text + dataRow[i].ToString().Trim() + "\t";
  29. }
  30. text = text.Substring(0, text.Length - 1) + "\n";
  31. current.Response.Output.Write(text);
  32. }
  33. current.Response.Output.Flush();
  34. current.Response.End();
  35. }
  36. public static string Fun_Substring(object byInfo, int bylength)
  37. {
  38. if (byInfo.ToString().Length > bylength)
  39. {
  40. return byInfo.ToString().Substring(0, bylength) + "...";
  41. }
  42. else
  43. {
  44. return byInfo.ToString();
  45. }
  46. }
  47. }
  48. }