作者 何书鹏
1 个管道 的构建 通过 耗费 3 秒

合并分支 'heshupeng' 到 'master'

Heshupeng



查看合并请求 !279
... ... @@ -2,8 +2,16 @@
namespace app\admin\controller\user;
use app\admin\library\Auth;
use app\common\controller\Backend;
use app\common\model\User as UserModel;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
/**
* 会员管理
... ... @@ -449,4 +457,169 @@ class User extends Backend
$user = $this->model->where($where)->find();
return $user ? true : false;
}
/**
* 导入
*/
public function import()
{
$file = $this->request->request('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();
}
//导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
$importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
$table = $this->model->getQuery()->getTable();
$database = \think\Config::get('database.database');
$fieldArr = [];
$list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
foreach ($list as $k => $v) {
if ($importHeadType == 'comment') {
$fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
} else {
$fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
}
}
$fieldArr['手机号'] = 'mobile';
$fieldArr['真实姓名'] = 'nickname';
$fieldArr['密码'] = 'password';
$fieldArr['性别'] = 'sex';
$fieldArr['工作单位'] = 'work_address';
//加载文件
$insert = [];
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;
}
}
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 = [];
$temp = array_combine($fields, $values);
$temp = array_filter($temp); //过滤空行
foreach ($temp as $k => $v) {
if (isset($fieldArr[$k]) && $k !== '') {
$row[$fieldArr[$k]] = $v;
}
}
if ($row) {
$row['status'] = 'normal';
switch ($row['sex']){
case '男':
$row['sex'] = 1;
break;
case '女':
$row['sex'] = 2;
break;
}
$row['expirationtime'] = intval(($row['expirationtime'] - 25569) * 3600 * 24) - 28800; //转换成1970年以来的秒数
$insert[] = $row;
}
}
} catch (Exception $exception) {
$this->error($exception->getMessage());
}
if (!$insert) {
$this->error(__('No rows were updated'));
}
foreach ($insert as $k => $v){
if(empty($v['username'])){
$this->error('第'.($k+2).'行请填写用户名');
}
if(empty($v['password'])){
$this->error('第'.($k+2).'行请填写密码');
}
if (UserModel::getByUsername($v['username'])) {
$this->error('第'.($k+2).'行用户名已存在');
}
if (!empty($v['mobile']) && UserModel::getByMobile($v['mobile'])) {
$this->error('第'.($k+2).'行手机号已存在');
}
}
try {
//是否包含admin_id字段
$has_admin_id = false;
foreach ($fieldArr as $name => $key) {
if ($key == 'admin_id') {
$has_admin_id = true;
break;
}
}
if ($has_admin_id) {
$auth = Auth::instance();
foreach ($insert as &$val) {
if (!isset($val['admin_id']) || empty($val['admin_id'])) {
$val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
}
}
}
$this->model->saveAll($insert);
} catch (PDOException $exception) {
$msg = $exception->getMessage();
if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
$msg = "导入失败,包含【{$matches[1]}】的记录已存在";
};
$this->error($msg);
} catch (Exception $e) {
$this->error($e->getMessage());
}
$this->success();
}
}
... ...
... ... @@ -14,6 +14,8 @@
<!--<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li>-->
<!--</ul>-->
<!--</div>-->
<a href="javascript:;" class="btn btn-danger btn-import {:$auth->check('user/user/import')?'':'hide'}" title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> {:__('Import')}</a>
<a href="/assets/import_moudle/用户数据导入.xlsx" class="btn btn-danger {:$auth->check('user/user/import')?'':'hide'}" title="{:__('导入模板')}"> {:__('导入模板')}</a>
<a href="javascript:;" class="btn btn-default" style="font-size:14px;color:dodgerblue;">
<span class="extend">
用户数量:<span id="total">0</span>
... ...
... ... @@ -10,6 +10,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
edit_url: 'user/user/edit',
del_url: 'user/user/del',
multi_url: 'user/user/multi',
import_url: 'user/user/import',
table: 'user',
}
});
... ... @@ -45,7 +46,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
{checkbox: true},
{field: 'id', title: __('Id'), sortable: true},
// {field: 'group.name', title: __('Group')},
{field: 'username', title: __('用户名'), operate:false},
{field: 'username', title: __('用户名'), operate:'LIKE'},
{field: 'nickname', title: __('真实姓名'), operate:'LIKE'},
{field: 'password', title: __('密码'), operate:false},
{field: 'card', title: __('身份证'), operate:false},
... ...