作者 zhangyang

修改导入

@@ -42,142 +42,7 @@ class Study extends Backend @@ -42,142 +42,7 @@ class Study extends Backend
42 $this->view->assign("genderList", $this->model->getGenderList()); 42 $this->view->assign("genderList", $this->model->getGenderList());
43 } 43 }
44 44
45 - public function import(){  
46 - return parent::import();  
47 - }  
48 45
49 -// /*  
50 -// * 导入  
51 -// */  
52 -// public function import(){  
53 -// $file = $this->request->request('file');  
54 -// if (!$file) {  
55 -// $this->error(__('Parameter %s can not be empty', 'file'));  
56 -// }  
57 -// $filePath = ROOT_PATH . DS . 'public' . DS . $file;  
58 -// if (!is_file($filePath)) {  
59 -// $this->error(__('No results were found'));  
60 -// }  
61 -// //实例化reader  
62 -// $ext = pathinfo($filePath, PATHINFO_EXTENSION);  
63 -// if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {  
64 -// $this->error(__('Unknown data format'));  
65 -// }  
66 -// if ($ext === 'csv') {  
67 -// $file = fopen($filePath, 'r');  
68 -// $filePath = tempnam(sys_get_temp_dir(), 'import_csv');  
69 -// $fp = fopen($filePath, 'w');  
70 -// $n = 0;  
71 -// while ($line = fgets($file)) {  
72 -// $line = rtrim($line, "\n\r\0");  
73 -// $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);  
74 -// if ($encoding !== 'utf-8') {  
75 -// $line = mb_convert_encoding($line, 'utf-8', $encoding);  
76 -// }  
77 -// if ($n == 0 || preg_match('/^".*"$/', $line)) {  
78 -// fwrite($fp, $line . "\n");  
79 -// } else {  
80 -// fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");  
81 -// }  
82 -// $n++;  
83 -// }  
84 -// fclose($file) || fclose($fp);  
85 -//  
86 -// $reader = new Csv();  
87 -// } elseif ($ext === 'xls') {  
88 -// $reader = new Xls();  
89 -// } else {  
90 -// $reader = new Xlsx();  
91 -// }  
92 -//  
93 -// //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name  
94 -// $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';  
95 -//  
96 -// $table = $this->model->getQuery()->getTable();  
97 -// $database = \think\Config::get('database.database');  
98 -// $fieldArr = [];  
99 -// $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);  
100 -// foreach ($list as $k => $v) {  
101 -// if ($importHeadType == 'comment') {  
102 -// $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取  
103 -// $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];  
104 -// } else {  
105 -// $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];  
106 -// }  
107 -// }  
108 -//  
109 -// //加载文件  
110 -// $insert = [];  
111 -// try {  
112 -// if (!$PHPExcel = $reader->load($filePath)) {  
113 -// $this->error(__('Unknown data format'));  
114 -// }  
115 -// $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表  
116 -// $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号  
117 -// $allRow = $currentSheet->getHighestRow(); //取得一共有多少行  
118 -// $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);  
119 -// $fields = [];  
120 -// for ($currentRow = 1; $currentRow <= 1; $currentRow++) {  
121 -// for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {  
122 -// $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();  
123 -// $fields[] = $val;  
124 -// }  
125 -// }  
126 -//  
127 -// for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {  
128 -// $values = [];  
129 -// for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {  
130 -// $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();  
131 -// $values[] = is_null($val) ? '' : $val;  
132 -// }  
133 -// $row = [];  
134 -// $temp = array_combine($fields, $values);  
135 -// foreach ($temp as $k => $v) {  
136 -// if (isset($fieldArr[$k]) && $k !== '') {  
137 -// $row[$fieldArr[$k]] = $v;  
138 -// }  
139 -// }  
140 -// if ($row) {  
141 -// $insert[] = $row;  
142 -// }  
143 -// }  
144 -// } catch (Exception $exception) {  
145 -// $this->error($exception->getMessage());  
146 -// }  
147 -// if (!$insert) {  
148 -// $this->error(__('No rows were updated'));  
149 -// }  
150 -//  
151 -// try {  
152 -// //是否包含admin_id字段  
153 -// $has_admin_id = false;  
154 -// foreach ($fieldArr as $name => $key) {  
155 -// if ($key == 'admin_id') {  
156 -// $has_admin_id = true;  
157 -// break;  
158 -// }  
159 -// }  
160 -// if ($has_admin_id) {  
161 -// $auth = Auth::instance();  
162 -// foreach ($insert as &$val) {  
163 -// if (!isset($val['admin_id']) || empty($val['admin_id'])) {  
164 -// $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;  
165 -// }  
166 -// }  
167 -// }  
168 -// $this->model->saveAll($insert);  
169 -// } catch (PDOException $exception) {  
170 -// $msg = $exception->getMessage();  
171 -// if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {  
172 -// $msg = "导入失败,包含【{$matches[1]}】的记录已存在";  
173 -// };  
174 -// $this->error($msg);  
175 -// } catch (Exception $e) {  
176 -// $this->error($e->getMessage());  
177 -// }  
178 -//  
179 -// $this->success();  
180 -// }  
181 46
182 /** 47 /**
183 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法 48 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
@@ -454,5 +319,143 @@ class Study extends Backend @@ -454,5 +319,143 @@ class Study extends Backend
454 // } 319 // }
455 // } 320 // }
456 321
  322 + /**
  323 + * 导入
  324 + *
  325 + * @return void
  326 + * @throws PDOException
  327 + * @throws BindParamException
  328 + */
  329 + protected function import()
  330 + {
  331 +// set_time_limit();
  332 + $file = $this->request->request('file');
  333 + if (!$file) {
  334 + $this->error(__('Parameter %s can not be empty', 'file'));
  335 + }
  336 + $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  337 + if (!is_file($filePath)) {
  338 + $this->error(__('No results were found'));
  339 + }
  340 + //实例化reader
  341 + $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  342 + if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  343 + $this->error(__('Unknown data format'));
  344 + }
  345 + if ($ext === 'csv') {
  346 + $file = fopen($filePath, 'r');
  347 + $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  348 + $fp = fopen($filePath, 'w');
  349 + $n = 0;
  350 + while ($line = fgets($file)) {
  351 + $line = rtrim($line, "\n\r\0");
  352 + $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  353 + if ($encoding !== 'utf-8') {
  354 + $line = mb_convert_encoding($line, 'utf-8', $encoding);
  355 + }
  356 + if ($n == 0 || preg_match('/^".*"$/', $line)) {
  357 + fwrite($fp, $line . "\n");
  358 + } else {
  359 + fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  360 + }
  361 + $n++;
  362 + }
  363 + fclose($file) || fclose($fp);
  364 +
  365 + $reader = new Csv();
  366 + } elseif ($ext === 'xls') {
  367 + $reader = new Xls();
  368 + } else {
  369 + $reader = new Xlsx();
  370 + }
  371 +
  372 + //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  373 + $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  374 +
  375 + $table = $this->model->getQuery()->getTable();
  376 + $database = \think\Config::get('database.database');
  377 + $fieldArr = [];
  378 + $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  379 + foreach ($list as $k => $v) {
  380 + if ($importHeadType == 'comment') {
  381 + $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
  382 + $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  383 + } else {
  384 + $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  385 + }
  386 + }
  387 +
  388 + //加载文件
  389 + $insert = [];
  390 + try {
  391 + if (!$PHPExcel = $reader->load($filePath)) {
  392 + $this->error(__('Unknown data format'));
  393 + }
  394 + $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  395 + $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  396 + $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  397 + $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  398 + $fields = [];
  399 + for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  400 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  401 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  402 + $fields[] = $val;
  403 + }
  404 + }
  405 +
  406 + for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  407 + $values = [];
  408 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  409 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  410 + $values[] = is_null($val) ? '' : $val;
  411 + }
  412 + $row = [];
  413 + $temp = array_combine($fields, $values);
  414 + foreach ($temp as $k => $v) {
  415 + if (isset($fieldArr[$k]) && $k !== '') {
  416 + $row[$fieldArr[$k]] = $v;
  417 + }
  418 + }
  419 + if ($row) {
  420 + $insert[] = $row;
  421 + }
  422 + }
  423 + } catch (Exception $exception) {
  424 + $this->error($exception->getMessage());
  425 + }
  426 + if (!$insert) {
  427 + $this->error(__('No rows were updated'));
  428 + }
  429 +
  430 + try {
  431 + //是否包含admin_id字段
  432 + $has_admin_id = false;
  433 + foreach ($fieldArr as $name => $key) {
  434 + if ($key == 'admin_id') {
  435 + $has_admin_id = true;
  436 + break;
  437 + }
  438 + }
  439 + if ($has_admin_id) {
  440 + $auth = Auth::instance();
  441 + foreach ($insert as &$val) {
  442 + if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  443 + $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  444 + }
  445 + }
  446 + }
  447 + $this->model->saveAll($insert);
  448 + } catch (PDOException $exception) {
  449 + $msg = $exception->getMessage();
  450 + if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  451 + $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  452 + };
  453 + $this->error($msg);
  454 + } catch (Exception $e) {
  455 + $this->error($e->getMessage());
  456 + }
  457 +
  458 + $this->success();
  459 + }
457 460
458 } 461 }
@@ -123,8 +123,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin @@ -123,8 +123,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
123 success: function (res) { 123 success: function (res) {
124 if (res.code === 1) { 124 if (res.code === 1) {
125 var domain = window.location.href.split(':')[0] + '://' + document.domain; 125 var domain = window.location.href.split(':')[0] + '://' + document.domain;
126 - // var url = domain + '/uploads/20231011/fee9458c29cdccf10af7ec01155dc7f0.png';  
127 - var url = domain + '/uploads/20230524/f57ebce8a72b823912904fe76eda0909.png'; 126 + var url = domain + '/uploads/20231011/fee9458c29cdccf10af7ec01155dc7f0.png';
  127 + // var url = domain + '/uploads/20230524/f57ebce8a72b823912904fe76eda0909.png';
128 // console.log(url); 128 // console.log(url);
129 var link = document.createElement('a'); 129 var link = document.createElement('a');
130 console.log(link); 130 console.log(link);