官网:https://phpspreadsheet.readthedocs.io/en/stable/
下载链接: https://github.com/PHPOffice/PhpSpreadsheet
推荐使用composer安装 composer repuire phpoffice/phpspreadsheet
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
*上传方法
*/
public function import()
{
// 获取表单上传文件
$file = $this->request->file('file');
if ($file) {
$path = ROOT_PATH . 'public' . DS . 'uploads'; // 框架应用根目录/public/uploads/ 目录路径
$info = $file->move($path);// 移动到这个路径下
if ($info) {
$filename = $info->getSaveName(); // 获取上传后保存的文件名称
$inputFileName = $path . DS . $filename; // 文件上传后的文件信息
$spreadsheet = IOFactory::load($inputFileName); // Load $inputFileName to a Spreadsheet Object
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true); // 获取到格式类似于[{"A":...,"B":...},{...}]
// array_shift($sheetData);// 如果Excel里第一行有标题不使用可以去掉
foreach ($sheetData as $item) {
// 在这里进行数据处理
}
return 'success';
} else {
return $file->getError(); // 上传失败获取错误信息
}
}
}