ExcelCsv.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace app\common\library;
  3. class ExcelCsv{
  4. private $row;
  5. private $data;
  6. public function __construct($row,$data){
  7. $this->row[] = $row;
  8. $this->data = $data;
  9. }
  10. public function collection()
  11. {
  12. $row = $this->row;
  13. $data = $this->data;
  14. //设置表头
  15. foreach ($row[0] as $key => $value) {
  16. $key_arr[] = $key;
  17. }
  18. //输入数据
  19. foreach ($data as $key => &$value) {
  20. $js = [];
  21. for ($i=0; $i < count($key_arr); $i++) {
  22. $js = array_merge($js,[ $key_arr[$i] => $value[ $key_arr[$i] ] ]);
  23. }
  24. array_push($row, $js);
  25. unset($val);
  26. }
  27. $collect = collect($row);
  28. $row = [];
  29. $list = [];
  30. foreach ($collect as $key=>$item){
  31. $val = [];
  32. foreach ($item as $v){
  33. $val[] = $v;
  34. }
  35. if ($key == 0){
  36. $row[] = $val;
  37. }else{
  38. $list[] = $val;
  39. }
  40. }
  41. return $list;
  42. }
  43. public function download($fileName,$row,$list)
  44. {
  45. $fileName = $fileName.'.csv';
  46. //设置文件头
  47. header('Content-Description: File Transfer');
  48. header('Content-Type: application/vnd.ms-excel');
  49. header('Content-Disposition: attachment; filename="' . $fileName . '"');
  50. header('Expires: 0');
  51. header('Cache-Control: must-revalidate');
  52. header('Pragma: public');
  53. $fp = fopen('php://output', 'a');//打开output流
  54. mb_convert_variables('GBK', 'UTF-8', $row);
  55. fputcsv($fp, $row);
  56. foreach ($list as $val) {
  57. $val1 = [];
  58. foreach ($val as $export_obj) {
  59. $val1[] = iconv('utf-8', 'GB18030', $export_obj);
  60. }
  61. fputcsv($fp, $val1);
  62. //刷新缓冲
  63. ob_flush();
  64. flush();
  65. }
  66. fclose($fp);
  67. exit();
  68. }
  69. }