描述:下面import()方法是将上传的excel表转为一个二维数组,必须传入两个参数,参数1file_tmp为临时目录文件,我的excel表格第一行是描述,直接在方法中过滤掉。
1.要使用方法,首先引入类库,我用的是phpoffice
2.composer引入方法:项目中执行 composer require phpoffice/phpexcel
public function import($file,$file_tmp)
{
//获取文件后缀
$extension = strtolower( pathinfo($file, PATHINFO_EXTENSION) );
//定义可上次的文件后缀
$extensions = ['xlsx','xls'];
//判断文件后缀是否合法
if(!in_array($extension,$extensions)){
return '上传文件不合法';
}
$spreadsheet = IOFactory::load($file_tmp);
$sheet = $spreadsheet->getActiveSheet();
// $data = $sheet->getCellCollection ();
// $title = $sheet->getTitle();
// $data = $sheet->getColumnDimensions();
$highestRow = $sheet->getHighestRow(); // 总行数
$highestColumn = $sheet->getHighestColumn(); // 总列数
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$lines = $highestRow - 1;
if ($lines <= 0) {
return '表格为空';
}
for ($row = 2; $row <= $highestRow; ++$row) {
$rowData = [];
for ($column = 1; $column <= $highestColumnIndex; $column++) {
$model_no = $sheet->getCellByColumnAndRow($column, $row)->getValue();
$rowData[] = $model_no;
}
$rowData1[] = $rowData;
}
return $rowData1;
}
网友评论