php 读取excel数据

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;
}

猜你喜欢

转载自blog.csdn.net/angle_jian/article/details/80982548