Home Backend Development PHP Tutorial PHPExcel data export example

PHPExcel data export example

Jul 25, 2016 am 08:42 AM

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles