search
HomeBackend DevelopmentPHP TutorialPHPExcel data export example

1. getdata.php

  1. namespace WebadminModel;
  2. use ExtendSpaceExcel;
  3. slightly
  4. // Get data
  5. $dataBillArr = $this->get_list_bysql($sql);
  6. // Replace 0 and 1 in the data with yes and no
  7. // PHPExcel has a built-in method for processing, but the result is TRUE/FALSE, handle it yourself here
  8. $this->_formatZero($dataBillArr, array(' taxflag', 'payflag', 'removeflag'));
  9. // Replace payment status
  10. foreach ($dataBillArr as $key => $value) {
  11. switch ($value['statustype']) {
  12. case ' -1':
  13. $dataBillArr[$key]['statustype'] = 'Cancelled';
  14. break;
  15. case '-2':
  16. $dataBillArr[$key]['statustype'] = 'Cancelled and returned payment';
  17. break;
  18. case '0':
  19. $dataBillArr[$key]['statustype'] = 'Pending payment';
  20. break;
  21. case '1':
  22. $dataBillArr[$key]['statustype' ] = 'To be shipped';
  23. break;
  24. case '2':
  25. $dataBillArr[$key]['statustype'] = 'To be received';
  26. break;
  27. case '3':
  28. $dataBillArr[$ key]['statustype'] = 'Completed';
  29. break;
  30. case '10':
  31. $dataBillArr[$key]['statustype'] = 'Return completed';
  32. break;
  33. case '11':
  34. $dataBillArr[$key]['statustype'] = 'Refund completed';
  35. break;
  36. default:
  37. $dataBillArr[$key]['statustype'] = 'None';
  38. break;
  39. }
  40. }
  41. //Set the fields to be exported and the corresponding header names
  42. $header = array(
  43. array('title'=>'Platform order number', 'field'=>'billcode', 'type'=> 'string', 'autosize'=>true),
  44. array('title'=>'User account', 'field'=>'username', 'type'=>'string', 'autosize' =>true),
  45. array('title'=>'User Nickname', 'field'=>'nickname'),
  46. array('title'=>'Merchant', 'field'=> ;'shopuser', 'autosize'=>true),
  47. array('title'=>'Guanyi ERP order number', 'field'=>'erpsn', 'type'=>'string' , 'autosize'=>true),
  48. array('title'=>'Payment number', 'field'=>'bspaycode', 'type'=>'string', 'autosize'=> ;true),
  49. array('title'=>'Bonded batch number', 'field'=>'bsbatchcode', 'type'=>'string', 'autosize'=>true),
  50. array('title'=>'Is it cross-border', 'field'=>'taxflag'),
  51. array('title'=>'Order status', 'field'=>'statustype'),
  52. ……
  53. omitted
  54. ……
  55. );
  56. // Call the interface to perform Excel generation and export operations
  57. $filename = 'Order flow table_' . date('Y year m month d day_His', time( ));
  58. Excel::export($dataBillArr, $header, $filename);
Copy code


二、Excel.class.php

  1. namespace ExtendSpace;
  2. /**
  3. * Class Excel universal Excel interface, handles export and export operations
  4. * Instructions for use:
  5. * 1. Import
  6. * To be continued. . .
  7. * 2. Export
  8. * use ExtendSpaceExcel;
  9. * .....
  10. * Excel::export($dataArr, $header, $filename);
  11. *
  12. * @package ExtendSpace
  13. * @author xxxxx 2015-08- 27 14:07:14
  14. * @version
  15. */
  16. class Excel {
  17. // private static $objPHPExcel = null;
  18. /**
  19. * Entry file: Export Excel
  20. * @return
  21. */
  22. public static function export($data, $header, $filename='hms_excel_export') {
  23. //Introduce the PHPExcel class library
  24. import('phpexcel.PHPExcel', dirname(__FILE__) . '/', '.php'); // This is TP-specific and can be used directly include or require
  25. // Initial settings
  26. $objPHPExcel = new PHPExcel();
  27. $objPHPExcel->getProperties()->setCreator('test')->setLastModifiedBy('test'); // Set here Chinese garbled characters, not solved yet
  28. // ->setTitle('This is the title')
  29. // ->setSubject('What is this')
  30. // ->setDescription('This is the description')
  31. / / ->setKeywords('This is a keyword')
  32. // ->setCategory('Is this a directory');
  33. // var_dump($objPHPExcel->getProperties());exit;
  34. // Get the active worksheet currently being operated on
  35. $objActSheet = $objPHPExcel->getActiveSheet();
  36. // Write the table header
  37. foreach ($header as $k => $v) {
  38. $colIndex = self: :_getHeaderIndex($k);
  39. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colIndex . '1', $v['title']);
  40. // Whether the column needs to automatically adapt to the width
  41. if (!empty($v['autosize'])) {
  42. $objActSheet->getColumnDimension($colIndex)->setAutoSize(true);
  43. }
  44. }
  45. // Write data, starting from the second line , the first row is the header
  46. $rowNum = 2;
  47. foreach($data as $rows){ // Traverse the data and get a row
  48. foreach($header as $kk => $vv){ // Cell writing Enter
  49. $colIndex = self::_getHeaderIndex($kk);
  50. // Whether to specify the cell data format
  51. if (!empty($vv['type'])) { // Yes
  52. switch ($vv[' type']) {
  53. case 'number':
  54. $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; // Number
  55. break;
  56. case 'boolean':
  57. $type = PHPExcel_Cell_DataType::TYPE_BOOL; // Boolean value, 0-> FALSE; 1->TRUE
  58. break;
  59. default:
  60. $type = PHPExcel_Cell_DataType::TYPE_STRING; // String
  61. break;
  62. }
  63. $objActSheet->setCellValueExplicit($colIndex.$rowNum, $rows[$vv ['field']], $type);
  64. } else { // No, default normal
  65. $objActSheet->setCellValue($colIndex.$rowNum, $rows[$vv['field']]);
  66. }
  67. }
  68. $rowNum++;
  69. }
  70. // Set row height rownum
  71. // $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
  72. // Set font And style
  73. $objActSheet->getDefaultStyle()->getFont()->setSize(12); // Overall font size
  74. $objActSheet->getStyle('A1:' . self::_getHeaderIndex(count($ header)) . '1')->getFont()->setBold(true); // Make the column header bold
  75. // Set the worksheet name
  76. $objActSheet->setTitle('Sheet1');
  77. // Set header header parameters
  78. // header("Pragma: public");
  79. // header("Expires: 0");
  80. // header("Cache-Control:must-revalidate, post-check=0 , pre-check=0");
  81. // header("Content-Type:application/force-download");
  82. // header("Content-Type:application/vnd.ms-execl");
  83. // header("Content-Type:application/octet-stream");
  84. // header("Content-Type:application/download");;
  85. // header('Content-Disposition:attachment;filename="' . $ savedFileName . '"');
  86. // header("Content-Transfer-Encoding:binary");
  87. // Final output
  88. $savedFileName = self::_iconv($filename) . '.xls'; // Export File name + extension
  89. header('Content-Type: application/vnd.ms-excel');
  90. header('Content-Disposition: attachment;filename="' . $savedFileName . '"');
  91. header( 'Cache-Control: max-age=0');
  92. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  93. $objWriter->save('php://output');
  94. / / $objWriter->save($savedFileName);
  95. }
  96. /**
  97. * Entry file: Import Excel
  98. * @return
  99. */
  100. public static function import() {
  101. // 引入 PHPExcel 类库
  102. // import('phpexcel.PHPExcel', dirname(__FILE__) . '/', '.php');
  103. }
  104. private static function _init() {
  105. }
  106. /**
  107. * Get the header index value, that is: A, B, C..., greater than
  108. * @param array $header Array used to set the header
  109. * @return string
  110. */
  111. private function _getHeaderIndex($num) {
  112. return PHPExcel_Cell::stringFromColumnIndex($num);
  113. }
  114. /**
  115. * Character conversion to avoid garbled characters
  116. * @param string $str Characters to be processed
  117. * @return string
  118. */
  119. private function _iconv($str) {
  120. return iconv('utf-8', 'gb2312', $str);
  121. }
  122. }
复制代码



PHPExcel


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use