zl程序教程

您现在的位置是:首页 >  工具

当前栏目

phpoffice/phpexcel 读取Excel表格数据

Excel数据 读取 表格 PHPExcel
2023-06-13 09:16:43 时间

站长源码网

1. 使用示例


TP5.0

$file = request()->file('file');
$data = Excel::read($file->getRealpath());

2. 封装类


<?php
/**
* 导入数据
* composer require phpoffice/phpexcel
* PHP7.2版本以下推荐使用 phpoffice/phpexcel
* PHP7.2版本以上推荐使用 phpoffice/phpspreadsheet
*/
class Excel
{
/**
* 读取表格数据
* @param string 临时文件路径
* @return array
*/
public static function read($file)
{
// 设置excel格式
$reader = PHPExcel_IOFactory::createReader('Excel5');
// 载入excel文件
$excel = $reader->load($file);
// 读取第一张表
$sheet = $excel->getSheet(0);
// 获取总行数
$row_num = $sheet->getHighestRow();
// 获取总列数
$col_num = $sheet->getHighestColumn();
$data = []; //数组形式获取表格数据
for ($col = 'A'; $col <= $col_num; $col++) {
for ($row = 2; $row <= $row_num; $row++) {
$data[$row - 2][] = $sheet->getCell($col . $row)->getValue();
}
}
return $data;
}
}