Export.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\common\library;
  4. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  5. use PhpOffice\PhpSpreadsheet\IOFactory;
  6. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  7. use PhpOffice\PhpSpreadsheet\Writer\Csv;
  8. class Export
  9. {
  10. /* @var Csv $writer */
  11. private $spreadsheet;
  12. private $column=[];
  13. private $data=[];
  14. private $searchList=[];
  15. public function __construct()
  16. {
  17. $this->spreadsheet=new Spreadsheet();
  18. }
  19. public function setColumn($column)
  20. {
  21. $this->column=$column;
  22. }
  23. public function setData($data,$searchList=[]){
  24. $this->data=$data;
  25. $this->searchList=$searchList;
  26. }
  27. public function write()
  28. {
  29. $worksheet = $this->spreadsheet->getActiveSheet();
  30. $i=0;
  31. foreach ($this->column as $column){
  32. $i++;
  33. $columnName = Coordinate::stringFromColumnIndex($i);
  34. $worksheet->setCellValue($columnName.'1', $column);
  35. }
  36. foreach ($this->data as $row=>$data){
  37. $lie=1;
  38. foreach ($this->column as $key=>$column){
  39. $value=$this->getLieValue($data,$key);
  40. if(key_exists($key,$this->searchList)){
  41. $value=key_exists($value,$this->searchList[$key])?$this->searchList[$key][$value]:$value;
  42. }
  43. $columnName = Coordinate::stringFromColumnIndex($lie);
  44. $worksheet->setCellValue($columnName.($row+2), $value);
  45. $lie++;
  46. }
  47. }
  48. }
  49. private function getLieValue($data,$key)
  50. {
  51. if(strpos($key,'.')!==false){
  52. $key=explode('.',$key);
  53. if(isset($data[$key[0]]) && isset($data[$key[0]][$key[1]])){
  54. return $data[$key[0]][$key[1]];
  55. }
  56. }else{
  57. if(isset($data[$key])){
  58. return $data[$key];
  59. }
  60. }
  61. return '';
  62. }
  63. public function save($path,$file)
  64. {
  65. $writer = IOFactory::createWriter($this->spreadsheet, 'Xlsx');
  66. $writer->save($path.$file);
  67. }
  68. public function output()
  69. {
  70. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  71. header('Content-Disposition: attachment;filename="'.date('YmdHis',time()).'.xlsx');
  72. header('Cache-Control: max-age=1');
  73. $writer = IOFactory::createWriter($this->spreadsheet, 'Xlsx');
  74. $writer->save('php://output');
  75. exit;
  76. }
  77. }