在对应控制层加上2个方法import跟readFile,注意需要把对应的方法引入一下
/**
* 重写import方法
*/
public function import()
{
$file = $this->request->request('file'); //'file'为文件字段名
$data = $this->readFile($file);
if (count($data) <= 0) {
$this->error(__('Parameter %s can not be empty', ''));
}
/*处理data数据*/
$nfc_num = 0;//需要投送的NFC数量(总数)
foreach ($data as $k=>$v){
$data[$k]['createtime'] = time();
$data[$k]['admin_id'] = $this->auth->getUserInfo()['id'];
$data[$k]['type'] = 2;
$nfc_num += $v['nfc_num'];
}
if ($nfc_num <= 0){
$this->error('NFC数量不能小于0');
}
$nfc_total = $this->configModel::getConfigField('nfc_total');//NFC总量
if ($nfc_total <= 0){
$this->error('NFC总量余量不足');
}
if ($nfc_total < $nfc_num){
$this->error('NFC总量不足投送');
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException()->validate($validate);
}
// dump($data);exit();
$result = $this->model->allowField(true)->saveAll($data);
$this->configModel = new Config();
$this->configModel::upDateConfigField('nfc_total',-$nfc_num);
foreach ($data as $param) {
change_user_nft_token($param['user_id'],$param['nfc_num'],'管理员投送');
}
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
}
/**
* 读取文件数据并返回
* @return array
*/
protected function readFile($file){
if (!$file) {
$this->error(__('Parameter %s can not be empty', 'file'));
}
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
if (!is_file($filePath)) {
$this->error(__('No results were found'));
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
$this->error(__('Unknown data format'));
}
if ($ext === 'csv') {
$file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w");
$n = 0;
while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding);
}
if ($n == 0 || preg_match('/^".*"$/', $line)) {
fwrite($fp, $line . "\n");
} else {
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
}
$n++;
}
fclose($file) || fclose($fp);
$reader = new Csv();
} elseif ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}
//加载文件
try {
if (!$PHPExcel = $reader->load($filePath)) {
$this->error(__('Unknown data format'));
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
//读取第一行字段名
$fields = [];
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[] = $val;
}
}
//读取行数据
$row = [];
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$values[] = is_null($val) ? '' : $val;
}
$row[] = array_combine($fields, $values);
}
} catch (Exception $exception) {
$this->error($exception->getMessage());
}
if (!$row) {
$this->error(__('No rows were updated'));
}
return $row;
}
在模板文件index中添加按钮
{:build_toolbar('import')}
在对应的js文件中添加好请求路径