PHPExcel环境准备
在PHP项目中读取Excel文件中的数据并不复杂,下面简要介绍具体的实现方法。
首先,需要下载并引入PHPExcel类库。这通常包含一个完整的文件夹以及核心的PHPExcel.php文件,确保这两个部分位于同一目录下以便正确引用。
读取Excel数据核心代码
require __DIR__ . './PHPExcel/IOFactory.php';
$PHPReader = new \PHPExcel_Reader_Excel2007();
//判断文件类型
if (!$PHPReader->canRead($filePath)) {
$PHPReader = new \PHPExcel_Reader_Excel5();
if (!$PHPReader->canRead($filePath)) {
echo 'no Excel';
return false;
}
}
$PHPExcel = $PHPReader->load($filePath);
/**读取excel文件中的第一个工作表*/
$currentSheet = $PHPExcel->getSheet(0);
/**取得最大的列号*/
$allColumn = $currentSheet->getHighestColumn();
/**取得一共有多少行*/
$allRow = $currentSheet->getHighestRow();
/**从第1行开始输出*/
for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
/**从第A列开始输出*/
for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue();
/**ord()将字符转为十进制数*/
$date[$currentRow - 1][] = $val;
}
}
return $date;
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持本站!