PHP Export data to Excel class

Source: Internet
Author: User
Export data to Excel, welcome to make Bricks
  1. /**
  2. * Exported to Excel file (generally exported in Chinese will be garbled, need to encode conversion)
  3. * Use the following method
  4. * $excel = new Excel ();
  5. * $excel->addheader (Array (' column 1 ', ' column 2 ', ' column 3 ', ' column 4 '));
  6. * $excel->addbody (
  7. Array
  8. Array (' Data 1 ', ' Data 2 ', ' Data 3 ', ' Data 4 '),
  9. Array (' Data 1 ', ' Data 2 ', ' Data 3 ', ' Data 4 '),
  10. Array (' Data 1 ', ' Data 2 ', ' Data 3 ', ' Data 4 '),
  11. Array (' Data 1 ', ' Data 2 ', ' Data 3 ', ' Data 4 ')
  12. )
  13. );
  14. * $excel->download ();
  15. */
  16. Class excel{
  17. Private $head;
  18. Private $body;
  19. /**
  20. *
  21. * @param type $arr one-dimensional array
  22. */
  23. Public Function AddHeader ($arr) {
  24. foreach ($arr as $headVal) {
  25. $headVal = $this->charset ($headVal);
  26. $this->head. = "{$headVal}\t";
  27. }
  28. $this->head. = "\ n";
  29. }
  30. /**
  31. *
  32. * @param type $arr two-dimensional array
  33. */
  34. Public Function Addbody ($arr) {
  35. foreach ($arr as $arrBody) {
  36. foreach ($arrBody as $bodyVal) {
  37. $bodyVal = $this->charset ($bodyVal);
  38. $this->body. = "{$bodyVal}\t";
  39. }
  40. $this->body. = "\ n";
  41. }
  42. }
  43. /**
  44. * Download Excel file
  45. */
  46. Public Function downLoad ($filename = ") {
  47. if (! $filename)
  48. $filename = Date (' Ymdhis ', Time ()). XLS ';
  49. Header ("Content-type:application/vnd.ms-excel");
  50. Header ("Content-disposition:attachment;filename= $filename");
  51. Header ("content-type:charset=gb2312");
  52. if ($this->head)
  53. Echo $this->head;
  54. Echo $this->body;
  55. }
  56. /**
  57. * Encoding Conversion
  58. * @param type $string
  59. * @return String
  60. */
  61. Public Function CharSet ($string) {
  62. Return Iconv ("Utf-8", "gb2312", $string);
  63. }
  64. }
  65. ?>
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.