简单封装一个读取excel表格通用方法,简单记录一下,以防忘记。
<?php
use PhpOffice\PhpSpreadsheet\IOFactory as PHPExcel_IOFactory;
function readExcelFile($filename)
{
$fileParts = pathinfo($filename);
$filetype = strtolower($fileParts['extension']);
if (strtolower($filetype)=='xls') {
$objReader = PHPExcel_IOFactory::createReader('Xls');
} elseif (strtolower($filetype)=='xlsx') {
$objReader = PHPExcel_IOFactory::createReader('Xlsx');
} elseif (strtolower($filetype)=='csv') {
$objReader = PHPExcel_IOFactory::createReader('Csv')
->setDelimiter(',')
->setInputEncoding('GBK')
->setEnclosure('"');
}
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$excelResult = [];
$startRow = 2;
for ($j = $startRow; $j <= $highestRow; $j++) {
for ($k = 'A'; $k <= $highestColumn; $k++) {
$excelResult[$j][$k] = (string)$objWorksheet->getCell("$k$j")->getValue();
}
}
return $excelResult;
}
如有bug或考虑不周的地方,请大神们不吝赐教
|