使用PhpOffice\PhpSpreadsheet读取excel数据

浏览:1758 时间:2019-10-13 15:32:34

PhpOffice\PhpSpreadsheet是一个PHP类库,用来帮助我们简单、高效实现从Excel读取Excel的数据和导出数据到Excel。也是我们日常开发中,经常会遇到的使用场景。

1、可通过composer安装: 

composer require phpoffice/phpspreadsheet

下面是封装的类方法,有具体的说明

<?php
/**
* 使用的是thinkphp框架
* 引用PhpOffice\PhpSpreadsheet类库
* 其实就是引入IOFactory.php文件
*/
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
* excel
*/
class ExcelHelper
{


/**
* 读取excel文件的数据
* $row:获取第几行开始的数据
* $file_path:excel文件的路径(最好绝对路径)
* index_arr:要读取的列;如 [0,1,2,3]
* $fields:读取的列对应的自定义变量名;如 ['id','name','sex','age']
* extra :可以为空
*/
public function get_excel_data($row, $file_path, $fields = [], $index_arr = [], $extra = [])
{
$objPHPExcel = IOFactory::load($file_path);
$data = $objPHPExcel->getSheet(0)->toArray();
$count = count($data);

$insert_batch = array();
for ($i = $row; $i < $count; $i++) {
$insert = array();
for($j = 0; $j < count($fields); $j ++) {
$insert += array($fields[$j] => $data[$i][$index_arr[$j]]);
}
$insert += $extra;
array_push($insert_batch, $insert);
}

return $insert_batch;

}

/**
* 读取excel文件的某一行的数据
* $row:第几行,从0开始
* $file_path:excel文件的路径(最好绝对路径)
* index_arr:要读取的列;如 [0,1,2,3]
* $fields:读取的列对应的自定义变量名;如 ['id','name','sex','age']
* extra :可以为空
*/
public function given_excel_data($row, $file_path, $fields = [], $index_arr = [], $extra = [])
{
$objPHPExcel = IOFactory::load($file_path);
$data = $objPHPExcel->getSheet(0)->toArray();
$count = $row+1;

$insert_batch = array();
for ($i = $row; $i < $count; $i++) {
$insert = array();
for($j = 0; $j < count($fields); $j ++) {
$insert += array($fields[$j] => $data[$i][$index_arr[$j]]);
}
$insert += $extra;
if (!empty($insert)){
array_push($insert_batch, $insert);
}
}

return $insert_batch;

}

/**
* 读取excel文件所有数据
* $file_path:excel文件的路径(最好绝对路径)
*/
public function get_excel_all_data($file_path){
$objPHPExcel = IOFactory::load($file_path);
$data = $objPHPExcel->getSheet(0)->toArray();
return $data;
}
}

excel表结构分析:


封装参数中的index_arr=[0,1,2,3,4,5]代表获取了6列数据

封装参数中的$row代表行数 从0开始 



标签: PhpOffice excel