使用 phpExcel 读取xls/xlsx文件到数据库

下载PHPExcel包

require_once  ROOT_PATH.'/include/PHPExcel/Classes/PHPExcel.php';
require_once  ROOT_PATH.'/include/PHPExcel/Classes/PHPExcel/IOFactory.php';
$file_path = '..'.$batch_file;  //必须要能找到该文件的位置

if (!file_exists($file_path)) {
    die('no file!');
}

//文件的扩展名
$ext = strtolower(pathinfo($file_path,PATHINFO_EXTENSION));

if($ext == 'xlsx'){
    $objReader=PHPExcel_IOFactory::createReader('Excel2007');
    $objPHPExcel = $objReader->load($file_path,'utf-8');
}elseif($ext == 'xls'){
    $objReader=PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load($file_path,'utf-8');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$num = 0;
for($j=3;$j<=$highestRow;$j++) {
    $str = '';
    for ($k = 'A'; $k <= $highestColumn; $k++) {
        $str .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue() . '\\';//读取单元格
    }
    $strs = explode("\\", $str);
    $add_data['xx'] = $strs[2];
    $add_data['xx'] = $strs[3];
    $data[]=$add_data;
    $num++;
}

*注意:如果出现读取失败,大都是因为文件位置不正确



你可能感兴趣的:(PHP)