PHPexcel import and export excel file

/*
import excel
*/
function importExcel($filepath){
    require_once "/Libs/ThinkPHP/Library/Vendor/PHPExcel/PHPExcel/IOFactory.php";
    if (!file_exists($filepath)) {
        exit("not found {$filepath}.\n");
    }
      
    $reader = PHPExcel_IOFactory::createReader('Excel5'); //Set in Excel5 format (Excel97-2003 workbook)
    $PHPExcel = $reader->load($filepath); // Load excel file
    $sheet = $PHPExcel->getSheet(0); // read the first sheet
    $highestRow = $sheet->getHighestRow(); // Get the total number of rows
    $highestColumn = $sheet->getHighestColumn(); // Get the total number of columns
     
    /* return data variable */  
    $return=array(
        "rows"=>$highestRow-1,
        "cols"=>$highestColumm,
        "colindex"=>strpos("ABCDEFGHIJKLMNOPQRSTUVWXYZ",$highestColumm)+1,
        "data"=>array(),
    );
    /** Loop to read the data of each cell */
    for ($row = 2; $row <= $highestRow; $row++){//The number of rows starts with row 1
        for ($column = 'A'; $column <= $highestColumm; $column++) {//The number of columns starts with column A
            $dataset[] = $sheet->getCell($column.$row)->getValue();
            //echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
            $return['data'][$row-2][$column]=$sheet->getCell($column.$row)->getValue();
        }
    }
    return $return;
}
/*
export to excel
$titles is a one-dimensional array
$data is a multidimensional array
*/
function exportExcel($titles=array(),$data=array(),$filename='icaodan'){
    require_once "/Libs/ThinkPHP/Library/Vendor/PHPExcel/PHPExcel.php";
    $objPHPExcel = new PHPExcel();
    #set header
    $rownum=1;
    $settiele=$objPHPExcel->setActiveSheetIndex(0);
    for($i=0;$i<count($titles);$i++){                      
        $colname=substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",$i,1);
        $settiele->setCellValue($colname.$rownum, $titles[$i]);
    }
    if(count($titles)>0){$rownum++;}
    // set row height     
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);
    foreach($data as $k => $v){
        $num=0;
        foreach($v as $key=>$val){
            $colname=substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",$num++,1);
            $settiele->setCellValue($colname.$rownum, $val);
        }
        $rownum++;
    }
    $objPHPExcel->getActiveSheet()->setTitle('User');
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611679&siteId=291194637