public function importFile()
{
$file = request()->file('file');
$params = $this->request->param(); //可以获取到参数
if (!$file) {
$this->error('请选择导入文件');
}
// 保存的文件路径
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
//获取文件路径
$filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . $info->getSaveName();
//找不到文件
if (!is_file($filePath)) {
$this->error('无相关记录');
}
//===========开始
$PHPReader = new \PHPExcel_Reader_Excel2007();
if (!$PHPReader->canRead($filePath)) {
$PHPReader = new \PHPExcel_Reader_Excel5();
if (!$PHPReader->canRead($filePath)) {
$PHPReader = new \PHPExcel_Reader_CSV();
if (!$PHPReader->canRead($filePath)) {
$this->error('未知格式');
}
}
}
$PHPExcel = $PHPReader->load($filePath); //加载文件
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn); //获取有多少列
//获取到上传的excel中的第一行作为列头
for ($currentRow = 1; $currentRow <= 1; ++$currentRow) {
for ($currentColumn = 0; $currentColumn < $maxColumnNumber; ++$currentColumn) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[] = $val;
}
}
//存总数据用的
$insert = [];
//循环总行数:currentRow 从第二行开始才是数据
for ($currentRow = 2; $currentRow <= $allRow; ++$currentRow) {
$values = []; //行数据
// 循环每行每列
for ($currentColumn = 0; $currentColumn < $maxColumnNumber; ++$currentColumn) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$values[] = is_null($val) ? '' : $val;
}
$row = [];
// 合并
$temp = array_combine($fields, $values);
foreach ($temp as $k => $v) {
if ($k !== '') {
$k = trim($k);
//获得key
$col = self::excel2dbColhandler($k);//传入Excel的列头名,返回对应的数据库字段
if ($col) {
$row[$col] = trim($v);
}
}
}
if ($row) {
$row['create_time'] = date('Y-m-d h:i:s');
$insert[] = $row;
}
}
// 获取要新增的model
$nowModel = $this->getNowModel($params['tbname']);
$nowModel->saveAll($insert);
unset($info); //开始释放变量
unlink($filePath); //删除文件
}
来源:oschina
链接:https://my.oschina.net/u/4322392/blog/3405731