有时候需要把excel的数据导入php中,可能是json或者是php变量使用。
PhpOffice的版本已经跟新了不少,整理一下新版可用的方法。
前面需要composer导入库
composer require phpoffice/phpspreadsheet
这里直接贴代码
use PhpOffice\PhpSpreadsheet\IOFactory;
class Excel{
public function main($file){
return $this->getExcel($file);
}
/**
* @param string $file excel文件名
* @param int $header 头部字段名位置
* @return array
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
* @author An Yang
* @time 2021/3/4 10:19
*/
protected function getExcel(string $file, int $header = 2)
{
//默认参数行数从0开始计算;
$header -= 1;
$objReader = IOFactory::createReader('Xlsx'); // 有Xls和Xlsx格式两种
$objPHPExcel = $objReader->load($file); //$file 可以是上传的表格,或者是指定的表格
// $cells 是包含 Excel 表格数据的数组
$cells = [];
foreach ($objPHPExcel->getWorksheetIterator() as $sheelId => $cell) {
//$cells[] = $cell->toArray();
$cellName = [];
foreach ($cell->toArray() as $key => $val) {
//排除标题上面的列
if ($key < $header) {
continue;
}
//获取表列字段名
if ($key == $header) {
$cellName = $val;
continue;
}
//字段赋值
$item = [];
foreach ($val as $key2 => $val2) {
$name = $cellName[$key2] ?? "";
if (empty($name)) {
continue;
}
$cells[$sheelId][$key][$name] = $val2;
}
}
}
return $cells;
}
}需要使用的excel表大概格式为如下
| 姓名 | 上午 | 下午 |
| name | am | pm |
| 张三 | 上班 | 上班 |
| 李四 | 迟到 | 上班 |
| 王五 | 上班 | 早退 |

