SystemPostLogic.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\app\logic\system;
  8. use plugin\saiadmin\app\model\system\SystemPost;
  9. use plugin\saiadmin\basic\BaseLogic;
  10. use plugin\saiadmin\exception\ApiException;
  11. use plugin\saiadmin\service\OpenSpoutWriter;
  12. use OpenSpout\Reader\XLSX\Reader;
  13. /**
  14. * 岗位管理逻辑层
  15. */
  16. class SystemPostLogic extends BaseLogic
  17. {
  18. /**
  19. * 构造函数
  20. */
  21. public function __construct()
  22. {
  23. $this->model = new SystemPost();
  24. }
  25. /**
  26. * 可操作岗位
  27. * @param array $where
  28. * @return array
  29. */
  30. public function accessPost(array $where = []): array
  31. {
  32. $query = $this->search($where);
  33. $query->field('id, id as value, name as label, name, code');
  34. return $this->getAll($query);
  35. }
  36. /**
  37. * 导入数据
  38. */
  39. public function import($file)
  40. {
  41. $path = $this->getImport($file);
  42. $reader = new Reader();
  43. try {
  44. $reader->open($path);
  45. $data = [];
  46. foreach ($reader->getSheetIterator() as $sheet) {
  47. $isHeader = true;
  48. foreach ($sheet->getRowIterator() as $row) {
  49. if ($isHeader) {
  50. $isHeader = false;
  51. continue;
  52. }
  53. $cells = $row->getCells();
  54. $data[] = [
  55. 'name' => $cells[0]->getValue(),
  56. 'code' => $cells[1]->getValue(),
  57. 'sort' => $cells[2]->getValue(),
  58. 'status' => $cells[3]->getValue(),
  59. ];
  60. }
  61. }
  62. $this->saveAll($data);
  63. } catch (\Exception $e) {
  64. throw new ApiException('导入文件错误,请上传正确的文件格式xlsx');
  65. }
  66. }
  67. /**
  68. * 导出数据
  69. */
  70. public function export($where = [])
  71. {
  72. $query = $this->search($where)->field('id,name,code,sort,status,create_time');
  73. $data = $this->getAll($query);
  74. $file_name = '岗位数据.xlsx';
  75. $header = ['编号', '岗位名称', '岗位标识', '排序', '状态', '创建时间'];
  76. $filter = [
  77. 'status' => [
  78. ['value' => 1, 'label' => '正常'],
  79. ['value' => 2, 'label' => '禁用']
  80. ]
  81. ];
  82. $writer = new OpenSpoutWriter($file_name);
  83. $writer->setWidth([15, 15, 20, 15, 15, 25]);
  84. $writer->setHeader($header);
  85. $writer->setData($data, null, $filter);
  86. $file_path = $writer->returnFile();
  87. return response()->download($file_path, urlencode($file_name));
  88. }
  89. }