Export.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace app\admin\controller\examples;
  3. use Throwable;
  4. use app\common\controller\Backend;
  5. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  6. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  7. /**
  8. * 导出测试管理
  9. */
  10. class Export extends Backend
  11. {
  12. /**
  13. * Export模型对象
  14. * @var object
  15. * @phpstan-var \app\admin\model\examples\Export
  16. */
  17. protected object $model;
  18. protected string|array $quickSearchField = ['id'];
  19. protected string|array $defaultSortField = 'weigh,desc';
  20. protected string|array $preExcludeFields = ['create_time', 'update_time'];
  21. public function initialize(): void
  22. {
  23. parent::initialize();
  24. $this->model = new \app\admin\model\examples\Export;
  25. }
  26. /**
  27. * 导出
  28. * @return void
  29. * @throws Throwable
  30. */
  31. public function export(): void
  32. {
  33. $list = $this->model->select()->toArray();
  34. $spreadsheet = new Spreadsheet();
  35. $sheet = $spreadsheet->getActiveSheet();
  36. $sheet->setCellValue([1, 1], 'ID');
  37. $sheet->setCellValue([2, 1], '名字');
  38. $sheet->setCellValue([3, 1], '性别');
  39. $sheet->setCellValue([4, 1], '日期');
  40. $h = 2;
  41. foreach ($list as $v) {
  42. $sheet->setCellValue([1, $h], $v['id']);
  43. $sheet->setCellValue([2, $h], $v['name']);
  44. $sheet->setCellValue([3, $h], $v['status'] == 1 ? '男' : '女');
  45. $sheet->setCellValue([4, $h], date('Y-m-d H:i:s', $v['create_time']));
  46. $h++;
  47. }
  48. $writer = new Xlsx($spreadsheet);
  49. $file = time() . '.xlsx';
  50. ob_end_clean();
  51. header('Content-Type: application/vnd.ms-excel');
  52. header('Access-Control-Expose-Headers:Content-Disposition');
  53. header('Content-Disposition: attachment;filename=' . $file);
  54. header('Cache-Control: max-age=0');
  55. $writer->save('php://output');
  56. $spreadsheet->disconnectWorksheets();
  57. }
  58. }