用PHPExcel读取excel表格

2017-06-18

PHPExcel这个神器,可以帮助我们用PHP程序轻松的使用excel表格。
在此仅提供读取Excel表格内容到内存的两种方式:

通过坐标获取单元格的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

require_once 'Excel/PHPExcel.php';
require_once 'Excel/PHPExcel/IOFactory.php';
require_once 'Excel/PHPExcel/Reader/Excel5.php';

if($fileExtensions==".xlsx"){
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
}else{
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
$objReader->setReadDataOnly(true);
}

$objPHPExcel = $objReader->load($filepath); //$filename可以是上传的文件,或者是指定的文件
$sheetCount = $objPHPExcel->getSheetCount();//获取所有工作表的个数

for($i = 0; $i < $sheetCount; $i++)//遍历Excels的sheet页
{
$sheet = $objPHPExcel->getSheet($i);
//获取sheet页的名字:$sheetName = $sheet->getTitle();
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$maxColumns = \PHPExcel_Cell::columnIndexFromString($highestColumn);

for($key = 1; $key <= $highestRow; $key++)
{
for($k = 0; $k < $maxColumns; $k++)
{
columnValue = $sheet->getCellByColumnAndRow($k, $key)->getValue();//获取数据
}
}
}

通过遍历的方式获取单元格的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//把上传的excel读进来,然后处理数据
require_once 'Excel/PHPExcel.php';
require_once 'Excel/PHPExcel/IOFactory.php';
require_once 'Excel/PHPExcel/Reader/Excel5.php';

if($fileExtensions=="xlsx"){
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
}else{
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
}


$objPHPExcel = $objReader->load($basepath.$_FILES['file']['name']); //$filename可以是上传的文件,或者是指定的文件
$sheetCount = $objPHPExcel->getSheetCount();//获取所有工作表的个数
for($i = 0; $i < $sheetCount; $i++)
{
$sheet = $objPHPExcel->getSheet($i);
//获取sheet页的名字:$sheetName = $sheet->getTitle();
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数

foreach($sheet->getRowIterator() as $key => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);

foreach ($cellIterator as $cell) {
if($key == 1)
{
$columnValue = (string)$cell->getValue();//获取数据
}
}
}
$colums = [];
            $goodsAttrRef = [];//excel中的技术参数数据存到内存中