Home > Backend Development > PHP Tutorial > PHPExcel data export example

PHPExcel data export example

WBOY
Release: 2016-07-25 08:42:35
Original
1106 people have browsed it

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


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template