背景
在许多项目都会使用的文件上传功能,遂记之。
public function getExcel()
{
//接收上传文件
if (empty($_FILES["file"]["name"])) {
throw new ParamsException('上传文件为空');
}
$allowedExts = array("xlsx", "xls", "csv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp); // 获取文件后缀名
if (!in_array($extension, $allowedExts)) {
throw new ParamsException('非法的文件格式');
}
if ($_FILES["file"]["error"] > 0) {
throw new ParamsException($_FILES["file"]["error"]);
}
$file_name = "x_" . rand(1, 10) . "." . $extension;
$abs_file_name = "resource/" . $file_name;
move_uploaded_file($_FILES["file"]["tmp_name"], $abs_file_name);
return $abs_file_name;
}
public function _doneWetchRdr()
{
//接收上传文件
try {
$path = $this->getExcel();
} catch (ParamsException $e) {
return $this->rtJson(ErrDesc::ERR_UPLOAD_FILE, $e->getMessage());
}
// 加载 Excel 文件
$spreadsheet = IOFactory::load($path);
// 获取工作表
$worksheet = $spreadsheet->getActiveSheet();
// 获取最大行数和最大列
$highestRow = $worksheet->getHighestRow(); // 最大行号
$highestColumn = $worksheet->getHighestColumn(); // 最大列标识(如 'A', 'B', ..., 'Z', 'AA', 'AB', ...)
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // 将列标识转为数字
// 遍历每行每列
for ($row = 2; $row <= $highestRow; $row++) {
$col = 1;
$morderAR = new MatchWetechRdr();
$morderAR->wetech_id = $worksheet->getCellByColumnAndRow($col++, $row)->getValue() ?? '';
$morderAR->client_code = $worksheet->getCellByColumnAndRow($col++, $row)->getValue() ?? '';
$morderAR->ctime = time();
$morderAR->save();
}
}