作者 开飞机的舒克

后台导入功能优化

@@ -37,142 +37,11 @@ class Study extends Backend @@ -37,142 +37,11 @@ class Study extends Backend
37 } 37 }
38 38
39 39
40 - /**  
41 - * 导入 40 + /*
42 * 41 *
43 - * @return void  
44 - * @throws PDOException  
45 - * @throws BindParamException  
46 */ 42 */
47 - protected function import()  
48 - {  
49 - $file = $this->request->request('file');  
50 - if (!$file) {  
51 - $this->error(__('Parameter %s can not be empty', 'file'));  
52 - }  
53 - $filePath = ROOT_PATH . DS . 'public' . DS . $file;  
54 - if (!is_file($filePath)) {  
55 - $this->error(__('No results were found'));  
56 - }  
57 - //实例化reader  
58 - $ext = pathinfo($filePath, PATHINFO_EXTENSION);  
59 - if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {  
60 - $this->error(__('Unknown data format'));  
61 - }  
62 - if ($ext === 'csv') {  
63 - $file = fopen($filePath, 'r');  
64 - $filePath = tempnam(sys_get_temp_dir(), 'import_csv');  
65 - $fp = fopen($filePath, 'w');  
66 - $n = 0;  
67 - while ($line = fgets($file)) {  
68 - $line = rtrim($line, "\n\r\0");  
69 - $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);  
70 - if ($encoding !== 'utf-8') {  
71 - $line = mb_convert_encoding($line, 'utf-8', $encoding);  
72 - }  
73 - if ($n == 0 || preg_match('/^".*"$/', $line)) {  
74 - fwrite($fp, $line . "\n");  
75 - } else {  
76 - fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");  
77 - }  
78 - $n++;  
79 - }  
80 - fclose($file) || fclose($fp);  
81 -  
82 - $reader = new Csv();  
83 - } elseif ($ext === 'xls') {  
84 - $reader = new Xls();  
85 - } else {  
86 - $reader = new Xlsx();  
87 - }  
88 -  
89 - //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name  
90 - $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';  
91 -  
92 - $table = $this->model->getQuery()->getTable();  
93 - $database = \think\Config::get('database.database');  
94 - $fieldArr = [];  
95 - $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);  
96 - foreach ($list as $k => $v) {  
97 - if ($importHeadType == 'comment') {  
98 - $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取  
99 - $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];  
100 - } else {  
101 - $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];  
102 - }  
103 - }  
104 -  
105 - //加载文件  
106 - $insert = [];  
107 - try {  
108 - if (!$PHPExcel = $reader->load($filePath)) {  
109 - $this->error(__('Unknown data format'));  
110 - }  
111 - $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表  
112 - $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号  
113 - $allRow = $currentSheet->getHighestRow(); //取得一共有多少行  
114 - $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);  
115 - $fields = [];  
116 - for ($currentRow = 1; $currentRow <= 1; $currentRow++) {  
117 - for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {  
118 - $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();  
119 - $fields[] = $val;  
120 - }  
121 - }  
122 -  
123 - for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {  
124 - $values = [];  
125 - for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {  
126 - $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();  
127 - $values[] = is_null($val) ? '' : $val;  
128 - }  
129 - $row = [];  
130 - $temp = array_combine($fields, $values);  
131 - foreach ($temp as $k => $v) {  
132 - if (isset($fieldArr[$k]) && $k !== '') {  
133 - $row[$fieldArr[$k]] = $v;  
134 - }  
135 - }  
136 - if ($row) {  
137 - $insert[] = $row;  
138 - }  
139 - }  
140 - } catch (Exception $exception) {  
141 - $this->error($exception->getMessage());  
142 - }  
143 - if (!$insert) {  
144 - $this->error(__('No rows were updated'));  
145 - }  
146 -  
147 - try {  
148 - //是否包含admin_id字段  
149 - $has_admin_id = false;  
150 - foreach ($fieldArr as $name => $key) {  
151 - if ($key == 'admin_id') {  
152 - $has_admin_id = true;  
153 - break;  
154 - }  
155 - }  
156 - if ($has_admin_id) {  
157 - $auth = Auth::instance();  
158 - foreach ($insert as &$val) {  
159 - if (!isset($val['admin_id']) || empty($val['admin_id'])) {  
160 - $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;  
161 - }  
162 - }  
163 - }  
164 - $this->model->saveAll($insert);  
165 - } catch (PDOException $exception) {  
166 - $msg = $exception->getMessage();  
167 - if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {  
168 - $msg = "导入失败,包含【{$matches[1]}】的记录已存在";  
169 - };  
170 - $this->error($msg);  
171 - } catch (Exception $e) {  
172 - $this->error($e->getMessage());  
173 - }  
174 -  
175 - $this->success(); 43 + public function import(){
  44 + return parent::import();
176 } 45 }
177 46
178 /** 47 /**
@@ -272,7 +141,7 @@ class Study extends Backend @@ -272,7 +141,7 @@ class Study extends Backend
272 ->setCellValue('G' . $k, $val['earn_score']); 141 ->setCellValue('G' . $k, $val['earn_score']);
273 } 142 }
274 $excel->createSheet(); 143 $excel->createSheet();
275 - $title = "学生成绩" . date("YmdHis"); 144 + $title = "学生成绩" . date("Ymd");
276 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 145 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
277 header('Content-Disposition: attachment;filename="' . $title . '.xlsx"'); 146 header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
278 header('Cache-Control: max-age=0'); 147 header('Cache-Control: max-age=0');