require_once PI_ROOT . '/framework/library/phpexcel/PHPExcel.class.php';
/**
* 读取 Excel 文件
*
* @param string $filePath 要读取的路径
* @param integer $sheet 要读取的工作列表
* @return array
*/
function loadExcel($filePath = '', $sheet = 0)
{
$PHPReader = new PHPExcel_Reader_Excel2007;
if (!$PHPReader->canRead($filePath)) {
$PHPReader = new PHPExcel_Reader_Excel5();
if (!$PHPReader->canRead($filePath)) {
echo 'no Excel';
return;
}
}
$PHPExcel = $PHPReader->load($filePath); //建立excel对象
$currentSheet = $PHPExcel->getSheet($sheet); //**读取excel文件中的指定工作表*/
$allColumn = $currentSheet->getHighestColumn(); //**取得最大的列号*/
$allColumn = PHPExcel_Cell::columnIndexFromString($allColumn);//**取得最大的列号*/
$allRow = $currentSheet->getHighestRow(); //**取得一共有多少行*/
$data = array();
for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { //循环读取每个单元格的内容。注意行从2开始,列从A开始
for ($column = 0; $column < $allColumn; $column++) {
//通过数字获取对应 列号
$colIndex = PHPExcel_Cell::stringFromColumnIndex($column);
$addr = $colIndex . $rowIndex;//对应下标
$cell = $currentSheet->getCell($addr)->getValue();//获取对应值
if ($cell instanceof PHPExcel_RichText) { //富文本转换字符串
$cell = $cell->__toString();
}
$data[$rowIndex][$colIndex] = $cell;
}
}
return $data;
}php 读取excel数据
最新推荐文章于 2025-04-20 09:28:24 发布
博客给出了使用PHP读取Excel文件的代码。定义了loadExcel函数,可根据文件路径和工作表序号读取Excel内容。函数中会根据文件类型选择合适的读取器,然后获取工作表的最大列号和行数,循环读取每个单元格内容并存储在数组中返回。
536

被折叠的 条评论
为什么被折叠?



