使用PHPExcel导入数据到数据库

将PHPExcel放Thinkphp/Library/Org/Util下

/**
 * @param unknown $filename  //导入的文件 此外($_FILES['upload']['tmp_name']上传的Excel;
 * @param unknown $encode    //编码类型
 * @param unknown $file_type //文件类型xls或xlsx
 * @return array|string
 */
function read($filename,$encode,$file_type)
{
    import("Org.Util.PHPExcel");
    import("Org.Util.PHPExcel.IOFactory");
    if (strtolower($file_type) == 'xls')//判断excel表类型为2003还是2007
    {
        import("Org.Util.PHPExcel.Reader.Excel5");
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
    } elseif (strtolower($file_type) == 'xlsx') {
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
    }
    $objReader->setReadDataOnly(true);
    
    $objPHPExcel = $objReader->load($filename);
    
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    for ($row = 1; $row <= $highestRow; $row++) {
        for ($col = 0; $col < $highestColumnIndex; $col++) {
            $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
    }
    return $excelData;
}



你可能感兴趣的:(PHP)